Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Unit 2 Array Functions and Graphics

Chapter 2 covers arrays, functions, and graphics in PHP, detailing the definition, creation, and types of arrays including indexed, associative, and multidimensional arrays. It explains how to access and manipulate array elements, as well as functions like implode() and explode() for string manipulation. Additionally, it discusses sorting arrays and the array_flip() function to exchange keys and values.

Uploaded by

Geeta Birle
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Unit 2 Array Functions and Graphics

Chapter 2 covers arrays, functions, and graphics in PHP, detailing the definition, creation, and types of arrays including indexed, associative, and multidimensional arrays. It explains how to access and manipulate array elements, as well as functions like implode() and explode() for string manipulation. Additionally, it discusses sorting arrays and the array_flip() function to exchange keys and values.

Uploaded by

Geeta Birle
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 88

Chapter 2

Arrays , Functions and Graphics

Mrs.A.S.Shinde
Lecturer in Information
Technology
Array
➢ An array is a special variable that allow us to store more than one
value or a group of values of similar type in a single variable.
➢ For example if you want to store 100 numbers then instead of
defining 100 variables its easy to define an array of 100 length.
➢ Each array has starting indexes from 0 and so on:
➢ for each and for loops are used to access the values of an array.
➢ Each value in an array is called an element.
 You access each element via its index, which is a numeric or string
value. Every element in an array has its own unique index.
 An element can store any type of value, such as an integer, a string,
or a Boolean.You can mix types within an array — for example, the
first element can contain an integer, the second can contain a string,
and so on.
 An array’s length is the number of elements in the array.
Create an Array:

 In PHP, the array() function is used to create an array:


 Syntax:
variablename = array();
Example:
$colors = array(“Red”,”Green”,”Blue”);
Or
$colors=[“Red”,”Green”,”Blue”];
What is array? How to store data in array?
An array is a special variable that allow us to store more than one value
or a group of values of similar type in a single variable
An array in PHP is an ordered map where a map is a type that associates
values to keys.
In PHP, the array() function is used to create an array:
Syntax:
variablename = array();
Example:
$colors = array(“Red”,”Green”,”Blue”);

Ways to store an array.

Using array indices


Using array variable
<?php
<?php
$array[0] = 'Apple’;
$array_fruits= array('Apple', 'Orange', OR
$array[1] = 'Orange’;
'Watermelon', 'Mango’);
$array[2] = 'Watermelon’;
?>
$array[3] =‘Mango’;
?>
print_r($array);
Define Array. State its example.
Definition:An array is a special variable, which can hold more than one value
at a time.
Example:
1)Indexed array:
$colors = array("Red", "Green", "Blue");
2)Associative array:
$student_one = array("Maths"=>95, "Physics"=>90, "Chemistry"=>96,
"English"=>93, "Computer"=>98);
3)Multidimensional array
$movies =array( "comedy" =>array("Pink Panther", "John English"),
"action" =>array("Die Hard", "Expendables","Inception"),
"epic" =>array("The Lord of the rings")
);
Types of Arrays in PHP
Explain Indexed array and associative arrays with suitable examples.
 There are three types of arrays that you can create. These are:
1. Indexed array — An array with a numeric key.
2. Associative array — An array where each key has its own specific value.
3. Multidimensional array — An array containing one or more arrays within
itself.
✓ Indexed Arrays
 An indexed or numeric array stores each array element with a numeric index.
 Typically the indices in an indexed array start from zero, so the first element
has an index of 0, the second has an index of 1, and so on
 Syntax:
array_name = array(“value1”,”value2”,”value3”,”value4”)
• There are two ways of creating an indexed array:
1. $colors = array(“Red”, “Green”, “Blue”);
2. $colors[0] = "Red";
$colors[1] = "Green";
$colors[2] = "Blue";
Example
<body>
<?php
/* First method to create array. */
$num = array( 1, 2, 3, 4, 5);
foreach( $num as $value )
{
echo "Value is $value <br />";
}
/* Second method to create array. */
$num [0] = "one";
$num [1] = "two";
$num [2] = "three";
$num [3] = "four";
$num [4] = "five";
foreach( $num as $value )
{
echo "Value is $value <br />";
}
?>
</body>
</html>
 Count Length of PHP Indexed Array PHP provides
count() function which returns length of an array.
 Example:
<!DOCTYPE html>
<html>
<body>
<?php
$name = array(“AAA", “BBB", “CCC");
echo count($name);
?>
</body>
</html>
 Associative Arrays
➢ This array is in the form of a key-value pair, where the key is the index
of the array and the value is the element of the array.
➢ We can associate name/label with each array elements in PHP using =>
symbol.
➢ Such way, you can easily remember the element because each element
is represented by label than an incremented number.
➢ Syntax:
➢ $input = array(“key1”=>”value1”,
“key2”=>”value2”,
“key3”=>”value3”,
“key4”=>”value4”);
 The other way to declare an associative array without an array
keyword
 $input[$key1] = $value1;
$input[$key2] = $value2;
$input[$key3] = $value3;
$input[$key4] = $value4;
<?php
$input = array(
"Jan"=>31,
"Feb"=>28,
"Mar"=>31,
"Apr"=>30);
foreach($input as $in)
{
echo $in."<br>";}
?>
Write a program to create associative array
in PHP.
<?php
$a = array("sub1"=>23,"sub2"=>23,"sub3"=>12,"sub4"=>13);
echo "<br>";
echo "using foreach loop<br>";
foreach ($a as $key=>$x)
echo $key .' is ‘.$x;
echo '<br>';
echo "using for loop<br>";
$length= count($a);
echo "Count of elements=$length<br>";
for ($i=0;$i<$length;$i++)
echo "$a[$i]<br>";
?>
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array("AAA" => 2000, "BBB" => 1000, "CCC" => 500);
echo "Salary of AAA is ". $salaries['AAA'] . "<br />";
echo "Salary of BBB is ". $salaries['BBB']. "<br />";
echo "Salary of CCC is ". $salaries['CCC']. "<br />";
/* Second method to create array. */
$salaries['AAA'] = "high";
$salaries['BBB'] = "medium";
$salaries['CCC'] = "low";
echo "Salary of AAA is ". $salaries['AAA'] . "<br />";
echo "Salary of BBB is ". $salaries['BBB']. "<br />";
echo "Salary of CCC is ". $salaries['CCC']. "<br />";
?>
</body>
</html>
<?php
$myarray = array("AAAA", "BBBB", "CCCC",12);
print_r($myarray); It prints all the values of the array along with
their index number
echo "<br>";
foreach($myarray as $val)
echo $val; printes all the elements of the array.

echo "<br>";
var_dump($myarray); It prints the array with its index value, the data
type of each element, and length of each
?> element.
Multidimensional Array
➢ A multidimensional array is an array inside another array.
➢ It allows you to store tabular data in an array.
➢ PHP multidimensional array can be represented in the form of
matrix which is represented by row * column.
➢ Each index of the array holds another array.
➢ The array of an array is the multidimensional array or a 2D,3D
array or a nested array.
➢ The advantage of multidimensional arrays is that they allow us to
group related data together.
➢ Example

Roll No Name Class $Std_info = array


(
1 Ganesh IF3I array(1,“Ganesh”,”IF3I”),
array(2,”Radha”,”IF6I”),
2 Radha IF6I
array(3,”Mohan”,”IF2I”)
3 Mohan IF2I );
✓ One-dimensional array, the array contains elements but no arrays.

array(52, 41, 89, 63)


✓ Two Dimensional Array :The array contains elements in which one or more elements of it are arrays
In total, the arrays are two-level deep.
array (
array(7, 8, 9),
array(4, 5, 6),
array(1, 2, 3)
)
✓ Three-dimensional array, the outer array contains arrays as elements. These second level arrays, again
contain arrays as elements. In total, three levels deep.
array (
array (
array(1, 0, 9),
array(0, 5, 6),
array(1, 0, 3)
),
array(
array(0, 4, 6),
array(0, 0, 1),
array(1, 2, 7)
),
)
✓ For N-dimensional array, the depth of arrays would be N.
Access 1-D Array

<?php
$array1D = array(52, 41, 89, 63);
foreach ($array1D as $element)
{
echo $element;
echo "<br>";
}
?>
 Access 2D Array elements
<?php
$array2D = array(
array(7, 8, 9),
array(4, 5, 6),
array(1, 2, 3)
);

foreach ($array2D as $i)


{
foreach ($i as $element)
{
echo $element;
echo " ";
}
echo "<br>";
}
?>
 Access 3-D array elements
<?php
$array3D = array(
array (
array(1, 0, 9),
array(0, 5, 6),
array(1, 0, 3)
),
array (
array(0, 4, 6),
array(0, 0, 1),
array(1, 2, 7)
),
);

foreach ($array3D as $i)


{
foreach ($i as $j)
{
foreach ($aj as $element)
{
echo $element;
echo " ";
}
echo "<br>";
}
echo "<br>";
}
?>
<?php
$marks = array(
echo "Display Marks:<br>";
"Ram" => array(
foreach($marks as $val)
"A" => 95,
{
"B" => 85,
foreach($val as $element)
"C" => 74,
{
),
echo "$element";
"Ramesh" => array(
echo " ";
}
"A" => 78,
echo "<br>";
"B" => 98,
}
"C" => 46,
//print_r($marks);
),
?>

"Radha" => array(

"A" => 88,


"B" => 46,
"C" => 99,
),
implode() Function
 The implode() function takes an array, joins it with the given string, and
returns the joined string.
 Syntax
implode(separator,array)
 The implode function has two arguments.
seperator- the string which connects each array element
array - the array to be joined
<!DOCTYPE html>
<html>
<body>
<?php
$arr = array(‘Have',‘Wondeful',‘Day!');
echo implode(" ",$arr);
?>
</body>
</html>
<?php
$array = ['Breakfast', 'Lunch', 'Dinner'];
echo implode(',', $array);
?>
<!DOCTYPE html>
<html>
<body>
<?php
$arr = array('Have','A!','Wonderful','Day!');
echo implode(" ",$arr)."<br>";
echo implode("+",$arr)."<br>";
echo implode("-",$arr)."<br>";
echo implode("X",$arr);
?>
</body>
</html>
explode() function

 The explode() is a built in function in PHP used to break a


string into an array/ split a string in different strings.
 The explode() function splits a string based on a string
delimiter/separator, i.e. it splits the string wherever the
delimiter character occurs.
 It returns an array of strings by splitting a string by a
separator.
 Syntax:
explode (string $separator, string $originalString, int $limit)
There are three parameters passed in the explode() function, in
which two parameters are mandatory, and the last one is optional to pass.
 $separator: whenever this character is found in the
string, the string will be divided into parts.
 $originalString: This parameter holds the string which
is to be split into array.
 $limit: The $limit parameter specifies the number of
array elements to be returned. It can contain any
integer value (zero, positive, or negative).
<?php
$str = "Hello, welcome to PHP
Programming.";
print_r (explode (" ", $str));
?>
<?php
$str = "Hello My Name Is Ganesha.";
print_r (explode (" ",$str, 0));
echo "<br>";
print_r (explode (" ",$str, 4));
echo "<br>";
print_r (explode (" ",$str, -3));
echo "<br>";
?>
<?php
$str = "Hello, welcome to PHP
Programming.";
print_r (explode ("e", $str));
?>
implode explode
The implode() function takes an array, The explode() function breaks a string
joins it with the given string, and returns into an array.
the joined string.

Returns a string from elements of an Returns an array of strings


array
Syntax: Syntax:
implode(separator,array) explode(separator,string,limit)
Example: Example:
<?php <?php
$arr = $str = "Hello world. It's a beautiful day.";
array('Hello','World!','Beautiful','Day!'); print_r (explode(" ",$str));
echo implode(" ",$arr); ?>
?> Output:
Output: Array ( [0] => Hello
Hello World! Beautiful Day! [1] => world.
[2] => It’s
[3] => a
[4] => beautiful
[5] => day.
)
array_flip() Function
 The array_flip() function is used to exchange the keys with their
associated values in an array.
 The function returns an array in flip order, i.e. keys from array
become values and values from array become keys.
 Syntax
 array_flip ( $Myarray )
<?php
$a=array("Orange" => 100, "Apple" => 200, "Banana" =>
300, "Cherry" => 400);
$b=array_flip($a);
print_r($b);
?>
Sorting Array
 sort() - sort arrays in ascending order
For sorting indexed arrays
 rsort() - sort arrays in descending order
 asort() - sort associative arrays in ascending order,
according to the value For sorting
associative
 arsort() - sort associative arrays in descending order,
arrays by value
according to the value
 ksort() - sort associative arrays in ascending order,
according to the key For sorting
 krsort() - sort associative arrays in descending order, associative
arrays by Key
according to the key
sort() - sort arrays in ascending order

<?php
$numbers = array(14, 16, 22, 42, 10);
sort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++)
{
echo $numbers[$x];
echo "<br>";
}
?>
Write PHP script to sort any five
numbers using array function.
<?php
$a = array(1, 8, 9, 4, 5);
sort($a);
foreach($a as $i)
{
echo $i.’ ‘;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sorting PHP Indexed Array in Descending Order</title>
</head>
<body>
<?php
$colors = array("Red", "Green", "Blue", "Yellow");
sort($colors);
echo "Indexed Array in Ascending Order :";
foreach($colors as $key => $val)
{
echo "<br>$key = $val";
}
echo "<hr>";
rsort($colors);
echo "Indexed Array in Descending Order :";
foreach($colors as $key => $val)
{
echo "<br>$key = $val";
}
echo "<hr>";
l>
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
asort($age);
echo "Associative Array in Ascending Order by value :";
foreach($age as $key => $val)
{
echo "<br>$key = $val";
}
echo "<hr>";
arsort($age);
echo "Associative Array in Descending Order by value:";
foreach($age as $key => $val)
{
echo "<br>$key = $val";
}
echo "<hr>";
ksort($age);
echo "Associative Array in Ascending Order by Key:";
foreach($age as $key => $val)
{
echo "<br>$key = $val";
}
echo "<hr>";
krsort($age);
echo "Associative Array in Descending Order by Key:";
foreach($age as $key => $val)
{
echo "<br>$key = $val";
}
?>
</body>
</htm
array_combine() Function
 The array_combine() is an inbuilt function in PHP which is used to
combine two arrays and create a new array by using one array for
keys and another array for values.
 That is all elements of one array will be the keys of new array and
all elements of the second array will be the values of this new array.
<?php
$array1 = array("Ram", "Akash", "Rishav");
$array2 = array('24', '30', '45');
print_r(array_combine($array1, $array2));
?>
array_change_key_case() function
 The array_change_key_case() function is an inbuilt function in PHP and is used to
change case of all of the keys in a given array either to lower case or upper case.
 Syntax
array_change_key_case(array, case)
 array (mandatory): This parameter refers to the array whose key’s case is needed
to be changed.
 case (optional): This is an optional parameter and refers to the ‘case’ in which we
need to convert the keys of the array.
 This can take two values, either CASE_UPPER or CASE_LOWER. CASE_UPPER
value determines the uppercase and CASE_LOWER determines lowercase.
 If the convert_case parameter is not passed then it’s default value is taken which is
CASE_LOWER.
<?php
$array = array("Alinka" => 90, "Raghu" => 80, "SiTa" => 95, "MoHAn" => 85,
"Rushi" => 70);
print_r(array_change_key_case($array,CASE_UPPER));
echo "<hr>";
print_r(array_change_key_case($array,CASE_LOWER));
echo "<hr>";
print_r(array_change_key_case($array));
?>
array_count_values() function
 The array_count_values is used to count all the values of an array.
 Syntax:
array_count_values(input_array)

<?php
$subject =array('Math', 20, 30 ,20,'Math', 'Science', 'Geography');
print_r(array_count_values($subject));
?>
array_chunk() Function
 The array_chunk() function is an inbuilt function in PHP which is used to split an array
into parts or chunks of given size depending upon the parameters passed to the function.
 Syntax:
array_chunk( $array, $size, $pre_keys )
 $array: This parameter represents the array that is needed to be divided into chunks.
 $size: This parameter is an integer which defines the size of the chunks to be created.
 $pre_keys: This parameter takes Boolean value. When this parameter is set to TRUE then
the keys are preserved, otherwise the chunk is reindexed starting from 0.
<?php
$input_array = array('name1', 'name2', 'name3', 'name4', 'name5');
print_r(array_chunk($input_array,2));
?>
array_pop() function
 The array_pop() function is used to remove the last element of an array.
For an empty array, the function returns NULL.
 Syntax:
array_pop(array_name)

<?php $array1= array('Mathematics','Physics','Chemistry','Biology');


$subject=array_pop($array1);
print_r($array1);
?>
array_push() function
 The array_push() function is used to add one or more elements
onto the end of an array. The length of array increases by the
number of variables pushed.
 Syntax:
array_push(array_name, value1, value2...)
<?php
$array1= array('Mathematics','Physics');
array_push($array1,'Chemistry','Biology');
print_r($array1);
?>
array_reverse() function
 The array_reverse() function is used to reverse the order of the
elements in an array.
 Syntax:
array_reverse(array_name, preserve_keys)
<?php
$a= array(1,2,3,4,5);
$x = array_reverse($a,true);
$y = array_reverse($a);
print_r($x);
echo '</br> ';
print_r($y);
?>
array_search() function

 The array_search() function is used to search the array against the


given value. The function returns the first corresponding key if
successful.
 Syntax:
array_search(value_search, array_name)

<?php
$fruits = array(0 => 'Orange', 1=> 'Apple', 2 => 'Banana',3 => 'Cherry');
$result = array_search('Cherry', $fruits);
echo $result;
?>
array_shift() function
 The array_shift() function is used to remove the first element from
an array, and returns the value of the removed element.
 Syntax:
array_shift(array_name)

<?php
$fruits_list = array(0 => 'Orange', 1=> 'Apple', 2 => 'Banana',3 => 'Cherry');
$result= array_shift($fruits_list);
print_r($fruits_list);
echo '</br>'.$result;
?>
array_sum() function
 The array_sum() function is used to calculate the sum of values in
the array.
 Syntax:
array_sum(array_name)

sizeof() function
The sizeof() function is used to count the elements of an array or
the properties of an object. This function is an alias of count().

<?php
$a[0] = 'Language';
$a[1] = 'English';
$a[2] = 'Math';
$a[3] = 'Science';
$result = sizeof($a);
echo $result;
?>
array_unshift() function
 The array_unshift() is used to add one or more elements to the beginning
of an array.
 Syntax:
array_unshift(array1,value1,value2......valuen )

<?php
$fruits_list = array('Orange', 'Apple');
array_unshift($fruits_list, 'Banana', 'Cherry');
print_r($fruits_list);
?>
in_array() function
 The in_array() function is used to check whether a value exists in
an array or not.
 Syntax:
 in_array(search_value, array_name)
<?php
$number_list = array('16.10', '22.0', '33.45', '45.45');
if (in_array(22.0, $number_list))
{
echo "'22.0' found in the array";
}
?>
PHP Functions
➢ A Function is nothing but a 'block of statements' which generally
performs a specific task and can be used repeatedly in our program.
➢ Types of functions:
1. Built-in function
2. User defined function
3. Variable function
4. Anonymous function
 Built-in Functions: PHP has over 1000 built-in functions that can be called
directly, from within a script, to perform a specific task.
 Besides the built-in PHP functions, it is possible to create your own
functions.
 Apart from the built-in functions, PHP allows us to create our own
customized functions called the user-defined functions.
• A function is a block of statements that can be used repeatedly in a program.
• A function will not execute automatically when a page loads.
• A function will be executed by a call to the function.
Rules to name Functions
➢ A function name can only contain alphabets, numbers and
underscores. No other special character is allowed.
➢ The name should start with either an alphabet or an underscore. It
should not start with a number.
➢ function names are not case-sensitive.
➢ The opening curly brace { after the function name marks the start
of the function code, and the closing curly brace } marks the end of
function code.
➢ The function name must be unique
➢ The function name must not contain spaces
➢ It is considered a good practice to use descriptive function names.
User Defined Functions
 This function may be defined using syntax such as following:
<?php
function function_name()
{
// function code statements
}
?>
• user-defined function without any
parameter/argument:
<?php
function printMessage()
{
echo "Hello, How are you?";
}
printMessage();
?>
Define user defined function with example.
A function is a named block of code written in a program to perform
some specific tasks.
They take information as parameters, execute a block of statements or
perform operations on these parameters and return the result.
A function will be executed by a call to the function.
The function name can be any string that starts with a letter or
underscore followed by zero or more letters, underscores, and digits.
When a function is defined in a script, to execute the function,
programmer have to call it with its name and parameters if required
Syntax:
function function_name([parameters if
any])
{
Function body / statements to be executed Example:
} <?php
function display() // declare and define a function
{
echo "Hello,Welcome to function";
}
display(); // function call
?>
Define function. How to define user defined function
in PHP? Give example.
Definition: -A function is a block of code written in a program to perform some
specific task. They take information as parameters, execute a block of statements
or perform operations on these parameters and return the result. A function will
be executed by a call to the function.
Define User Defined Function in PHP: A user-defined function declaration starts
with the keyword function.
Syntax:
function functionName()
{
code to be executed;
}
Example:
<?php
function writeMsg()
{
echo "Welcome to PHP world!";
}
writeMsg(); // call the function
?>
 Function with argument/parameter:
Syntax:
<?php
function function_name(argument1, argument2)
{
// function code statements
}
?>
Example:
<?php
function Greeting($festival)
{
echo "Wish you a very Happy $festival";
}
echo "Hey Jai <br/>";
Greeting("Diwali");
echo "<br/>";
echo "Hey Jon <br/>";
Greeting("New Year");
?>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>

<?php
function Product($num1, $num2, $num3)
{
$pro = $num1 * $num2 * $num3;
echo "The product is $pro";
}
Product(2, 3, 5);

?>
 PHP user-defined function default parameter –PHP allows us
to set default argument values for function parameters.
 If we do not pass any argument for a parameter with default value
then PHP will use the default set value for this parameter in the
function call.
<?php
function Say_Hello($name="Radhika")
{
echo "Hello $name<br/>";
}
say_Hello("Rajesh");
say_Hello();//passing no value
say_Hello("Mohan");
?>
<?php
function sum($n1, $n2 = 0)
{
echo "The sum of the two numbers is: ";
echo $n1 + $n2 . "\n";
}
sum(20, 30);
echo "<br>";
sum(20);
?>
 Example for PHP user-defined function to return a
value from the function .
<?php
function add($a, $b)
{
$sum = $a + $b;
return $sum;
}
echo "5 + 10 = " . add(5, 10);
?>

<?php
function cube($len)
{
return $len*$len*$len;
}
echo "Cube: ".cube(4);
?>
Variable Function
 PHP support the concept of the variable function. This means that if
a variable name has parentheses appended to it, PHP will look for a
function with the same name as the whatever variable evaluate to,
and will attempt to execute it.
<?php
function Hello() {
echo “Welcome<br />";
}
$fun = "Hello";
$fun();
?>
Anonymous Function
➢ Whenever we define a function in PHP,we usually provide a name for it as
well.
➢ This name is used to call the function at a later time whenever we need it.
➢ An anonymous function is a function that doesn‘t have a name.
➢ There is no function name between the function keyword and the
opening parenthesis.
➢ There is a semicolon after the function definition.
➢ Syntax:
function($arg1,$arg2,….,$argN)
{
//The definition for the anonymous function

};
➢ Function is assigned to a variable, and called later
using the variable‘s name.
➢ When passed to another function that can then call it later, it is
known as a callback.
➢ Return it from within an outer function so that it can access
the outer function‘s variables.This is known as a closure.
Function is assigned to a variable

<?php
$var = function ($x)
{
return pow($x,3);
};
echo "cube of 3 = " . $var(3);
?>
Anonymous function as callback

A callback function is passed as an argument to another function and it is


then called inside another function.

<?php
$arr = [10,3,70,21,54];
usort ($arr, function ($x , $y)
{
return $x > $y;
}
);
foreach ($arr as $x)
{
echo $x . "\n";
}
?>
Anonymous function as closure

➢ Closure is also an anonymous function that can access variables outside its scope
with the help of use keyword.
<?php
$message = 'Hi';
$say = function () use ($message)
{
echo $message;
};
$say();
?>

<?php
$max=300;
$percent=function ($marks) use ($max)
{
return $marks*100/$max;
};
echo "marks=285 percentage=". $percent(285);
?>
String Functions
strlen() function : This function is used to find
number of characters in a string . While counting number characters
from string, function also considers spaces between words.
syntax :
strlen(string);
- string specify name of the string from which characters have to be
counted.
Example :
<?php
$str = "Welcome to PHP";
echo "Length of the string is:".strlen($str);
?>
str_word_count() function: This function is used to count
the number of words in a string.
syntax :
str_word_count(string,return,char);
string : It indicates string to be checked.
return :It is optional. It specifies the return value of the function.
0- default. Returns the number of words found.
1- returns an array with the words from the string.
2- returns an array where the key is the position of the word in
the string, and value is the actual word.
char : Optional. It specifies special characters to be considered as words.
Example:
<?php
$str = "Welcome to Studytonight";
echo "Number of words in the string are: ". str_word_count($str);
?>
strrev() function : This function is used to
reverse a string.
This function accepts string as an argument and returns a
reversed copy of it.
Syntax :
$strname=strrev($string variable/String );
Example :
<?php
$str4="Polytechnic";
$str5=strrev($str4);
echo "Orginal string is '$str4' and reverse of it is '$str5’”;
?>
str_replace() function : This function is
used to replace some characters with some other
characters in a string.
Syntax :
str_replace(findword,replace,string,count);
- Find word specify the value to find
- replace specify characters to be replaced
with search characters.
- string specify name of the string on which
find and replace has to be performed.
- count is optional . It indicates number of
occurrences replaced from a string.
Example :
<?php
$str="Welcome to poly";
$str2=str_replace("poly","msbte",$str);
echo $str2;
?>
strcmp() function : This function is used to
compare two strings with each other .
It is a case sensitive comparison.
Syntax :
$result= strcmp(string1,string2);
- string1 and string2 indicates strings to be
compared with each other.
This function returns 0 if both the strings are equal.
It returns a value <0 if string1 is less than string2
and >0 if string 1 is greater than string2
Example :
<?php
$str6="Welcome";
$str7="Welcome";
echo strcmp($str7,$str6);
?>
strpos() function : This function is used to find the
position of the first occurrence of specified word inside another string.
It returns False if word is not present in string.
It is a case sensitive function. by default, search starts with 0th position in
a string.
Syntax :
strpos(String,findstring,start);
- string specify string to be searched to find another word
- findstring specify word to be searched in specified first
parameter.
- start is optional . It specifies where to start the search in a
string. If start is a negative number then it counts from the
end of the string.
Example:
<?php
$str8="Welcome to Polytechnic";
$result=strpos($str8,"Poly",0);
echo $result;
?>
ucwords() function: This function is used to
convert first character of each word from the string into
uppercase.
Syntax :
$variable=ucwords($Stringvar);
Example :
<?php
$str9="welcome to poly for web based development";
echo ucwords($str9);
?>
strtoupper() function :This function is
used to convert any character of string into uppercase.
Syntax :
$variable=strtoupper($stringvar);
Example:
<?php
$str9="POLYtechniC";
echo strtoupper($str9); ?>
strtolower() function : This function is used to
convert any character of string into lowercase.
Syntax:
$variable=strtolower($stringvar);
Example :
<?php
$str9="POLYtechniC";
echo strtolower($str9);
?>

Q.Write a PHP program to 6marks


i) Calculate length of string
ii) Count number of words in string
Basic Graphics Concepts

An image is a rectangle of pixels of various colors. Colors are


identified by their position in the palette, an array of colors. Each
entry in the palette has three separate color values—one for red,
one for green, and one for blue. Each value ranges from 0 (this color
not present) to 255 (this color at full intensity).

Image files are rarely a straightforward dump of the pixels and the
palette. Instead, various file formats (GIF, JPEG, PNG, etc.) have been
created that attempt to compress the data somewhat to make
smaller files.
With 256 possible values for each of red, green, and blue, there are
16,777,216 possible colors for each pixel.
Creating and Drawing Images

Example is a script that generates a black-filled square.

<?php
$image = imagecreate(200, 200);
$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$black = imagecolorallocate($image, 0x00, 0x00, 0x00);
imagefilledrectangle($image, 50, 50, 150, 150, $black);
header("Content-Type: image/png");
imagepng($image);

Figure A black square on a white background


Images with Text
Often it is necessary to add text to images. GD has built-in fonts for
this purpose. Example adds some text to our black square image.

Example .Adding text to an image

<?php
$image = imagecreate(200, 200);
$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$black = imagecolorallocate($image, 0x00, 0x00, 0x00);

imagefilledrectangle($image, 50, 50, 150, 150, $black);


imagestring($image, 5, 50, 160, "A Black Box", $black);

header("Content-Type: image/png");
imagepng($image);
Figure shows the output of Example.
Scaling Images

There are two ways to change the size of an image.


The imagecopyresized() function is fast but crude, and may
lead to jagged edges in your new images.
The imagecopyresampled() function is slower, but features
pixel interpolation to give smooth edges and clarity to the
resized image. Both functions take the same arguments:
imagecopyresized(dest, src, dx, dy, sx, sy, dw, dh, sw, sh);
imagecopyresampled(dest, src, dx, dy, sx, sy, dw, dh, sw, sh);
The dest and src parameters are image handles. The
point (dx, dy) is the point in the destination image where the
region will be copied. The point (sx, sy) is the upper-left corner
of the source image. The sw, sh, dw, and dh parameters give the
width and height of the copy regions in the source and
destination.
Example
<?php
$source = imagecreatefromjpeg("php.jpg");
$width = imagesx($source);
$height = imagesy($source);
$x = $width / 2;
$y = $height / 2;
$destination = imagecreatetruecolor($x, $y);
imagecopyresampled($destination, $source, 0, 0, 0, 0,
$x, $y, $width, $height);
header("Content-Type: image/png");
imagepng($destination);

?>
Explain two functions to scale the given image.
imagecopyresized() function : It is an inbuilt function in PHP which is used to copy a
rectangular portion of one image to another image and resize it. dst_image is the destination
image, src_image is the source image identifier.
Syntax:
imagecopyresized(dst_image, src_image, dst_x, dst_y,src_x, src_y, dst_w,dst_h,src_w, src_h)
dst_image: It specifies the destination image resource.
src_image: It specifies the source image resource.
dst_x: It specifies the x-coordinate of destination point.
dst_y: It specifies the y-coordinate of destination point.
src_x: It specifies the x-coordinate of source point.
src_y: It specifies the y-coordinate of source point.
dst_w: It specifies the destination width.
dst_h: It specifies the destination height.
src_w: It specifies the source width.
src_h: It specifies the source height.
Example:
imagecopyresized($d_image,$s_image,0,0,50,50,200,200,$s_width, $s_height);
imagecopyresampled() function : It is used to copy a rectangular portion of one image
to another image, smoothly interpolating pixel values thatresize an image.
Syntax:
imagecopyresampled(dst_image, src_image, dst_x, dst_y,src_x, src_y,
dst_w,dst_h,src_w, src_h)
dst_image: It specifies the destination image resource.
src_image: It specifies the source image resource.
dst_x: It specifies the x-coordinate of destination point.
dst_y: It specifies the y-coordinate of destination point.
ṇsrc_x: It specifies the x-coordinate of source point.
src_y: It specifies the y-coordinate of source point.
dst_w: It specifies the destination width.
dst_h: It specifies the destination height.
src_w: It specifies the source width.
src_h: It specifies the source height.
Example:
imagecopyresampled($d_image,$s_image,0,0,50,50,200,200,$s_widt h,$s_height);
PDF
Adobe’s Portable Document Format (PDF) provides a popular way to
get a consistent look, both on screen and when printed, for
documents. This chapter shows how to dynamically create PDF files
with text, graphics, links, and more.

A Simple Example
Let’s start with a simple PDF document.
Example
simply places “Hello Out There!” on a page and then displays the
resulting PDF document.
Example 10-1.
<?php require("../fpdf/fpdf.php"); // path to fpdf.php
$pdf = new FPDF();
$pdf->addPage();
$pdf->setFont("Arial", 'B', 16);
$pdf->cell(40, 10, "Hello Out There!");
$pdf->output();
?>

You might also like