0% found this document useful (0 votes)
21 views

Chapter 2

An array in PHP is a special variable that can hold multiple values of the same data type under a single name. There are three types of arrays in PHP: indexed arrays which use numbers as keys, associative arrays which use named keys, and multidimensional arrays which contain one or more nested arrays. Arrays allow storing and accessing related data efficiently. Elements in arrays can be accessed using their numeric index or string key. The count() function returns the length of an array and loops like for and foreach can be used to iterate through array elements.

Uploaded by

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

Chapter 2

An array in PHP is a special variable that can hold multiple values of the same data type under a single name. There are three types of arrays in PHP: indexed arrays which use numbers as keys, associative arrays which use named keys, and multidimensional arrays which contain one or more nested arrays. Arrays allow storing and accessing related data efficiently. Elements in arrays can be accessed using their numeric index or string key. The count() function returns the length of an array and loops like for and foreach can be used to iterate through array elements.

Uploaded by

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

Unit – 02

Arrays,
Functions and
Graphics

43
PHP Array Definition:-
• Array in PHP is type of data structure that allow to store multiple elements of
same data type under a single variable thereby saving us the efforts of creating
a different variable for every data.
• An Array in PHP actually an ordered map. A map is a type that associates values
to keys.
• An array stores multiple values of similar type in one single variable which can
be accessed using their index or key.
• An array is a special variable, which can hold more than one value at a time.
• If you have a list of items (a list of car names, for example), storing the cars in
single variables could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";

44
PHP Array Definition:-
• However, what if you want to loop through the cars and find a
specific one? And what if you had not 3 cars, but 300?.
• The solution is to create an array!
• An array can hold many values under a single name, and you can
access the values by referring to an index number.
Create an Array in PHP:-
• In PHP, the array() function is used to create an array:
array();

45
PHP Array Type:-
• In PHP, there are three types of arrays:

Indexed arrays - Arrays with a numeric index


Associative arrays - Arrays with named keys
Multidimensional arrays - Arrays containing one or more arrays

46
Get The Length of an Array:-
• The count() function is used to • Example:-
return the length (the number
of elements) of an array: <?php
$cars = array("Volvo", "BMW",
• Output:- "Toyota");
3 echo count($cars);
?>

47
Indexed or Numeric Array:-
• An array with a numeric index • The index can be assigned
where values are stores linearly automatically (index always starts
• Numeric array use number as at 0), like this:
access key. $cars = array("Volvo", "BMW",
• Syntax 1:- "Toyota");
<?php • or the index can be assigned
manually:
$variable_name[n]=value;
$cars[0] = "Volvo";
?> $cars[1] = "BMW";
$cars[2] = "Toyota";

48
Indexed or Numeric Array:-
• Syntax 1 Example:- • Output:-
<?php Computer Engg.
$course[0] = “Computer Engg.”; Information Tech.
$course[1] = “Information Tech.”; Civil
$course[2] = “Civil”;
// Accessing the element directly
echo $course[0+, “<br>”;
echo $course[1], “<br>”;
echo $course[2], “<br>”;
?>
49
Indexed or Numeric Array:-
• Syntax 2:- • Example:-
<?php
$variable_name[n]=array(n=>value, <?php
……….); $course = array( 0=> “Computer Engg.”,
?> 1 => “Information Tech.”, 2 => “Civil”);
Output:- echo $course[0];
Computer Engg. ?>

50
Loop Through an Indexed Array:-
• To loop through and print all the • Example:-
values of an indexed array, you <?php
could use a for loop, like this:
$cars = array("Volvo", "BMW",
"Toyota");
• Output:-
$arrlength = count($cars);
Volvo
for($x = 0; $x < $arrlength; $x++)
BMW
{
Toyota
echo $cars[$x], "<br>";
}
?>
51
Associative Arrays:-
• This type of array is similar to • Syntax:-
indexed array but instead of
linear storage, every value can
be assigned with user define <?php
key of string type. $variable_name*‘key_name’+=value;
• Associative arrays are arrays
that use named keys that you $variable_name=array(‘key_name’
assign to them. => value,……….);
• An array with a string index ?>
where instead of linear storage,
each value assigned a specific
key.
52
Associative Arrays:-
• There are two ways to create • Example 1:-
an associative array: <?php
$age = array("Peter"=>"35", $age = array("Peter"=>"35",
"Ben"=>"37", "Joe"=>"43"); "Ben"=>"37", "Joe"=>"43");
Or:- echo “Ben age is=”, $age*“Ben”+;
$age['Peter'] = "35"; ?>
$age['Ben'] = "37"; Output:-
$age['Joe'] = "43"; Ben age is= 37

53
Loop Through an Associative Array:-
• To loop through and print all • Example:-
the values of an associative <?php
array, you could use a foreach $age = array("Peter"=>"35",
loop, like this:
"Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $x_value) {
• Output:- echo "Key=" . $x . ", Value=" .
Key=Peter, Value=35 $x_value;
Key=Ben, Value=37 echo "<br>";
Key=Joe, Value=43 }
?>
54
Multidimensional Arrays:-
• These are array that contain • Syntax:-
other nested array. array (
• An array which contain single
or multiple arrays within it an array (elements….),
can be accessed via multiple array (elements….),
indices. ………
• PHP supports multidimensional
arrays that are two, three, four, );
five, or more levels deep.
However, arrays more than
three levels deep are hard to
manage.
55
Multidimensional Arrays:-
• Example 1:- // accessing elements
<?php echo “Ram Email id is:”
// Define multidimension array .$person*0+*“email’”+
$person = array( echo “Laxman Age is:”
array(“name => “Ram”, “age” => .$person*1+*“age’”+
“20”, “email” => [email protected]”),
array(“name => “Laxman”, “age” =>
?>
“18”, “email” => [email protected]”), Output:-
array(“name => “Sita”, “age” => “19”, Ram Email id is: [email protected]
“email” => [email protected]”)
Laxman Age is: 18
);

56
Accessing Multidimensional Arrays elements:-
• First, take a look at the • We can store the data from the table
following table: above in a two-dimensional array, like
this:
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
• Now the two-dimensional $cars array
contains four arrays, and it has two
indices: row and column.

57
Accessing Multidimensional Arrays elements:-
• To get access to the elements
of the $cars array we must echo $cars[0][0].": In stock:
point to the two indices (row ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
and column):
echo $cars[1][0].": In stock:
".$cars[1][1].", sold: ".$cars[1][2].".<br>";
<?php
$cars = array ( echo $cars[2][0].": In stock:
".$cars[2][1].", sold: ".$cars[2][2].".<br>";
array("Volvo",22,18),
array("BMW",15,13), echo $cars[3][0].": In stock:
".$cars[3][1].", sold: ".$cars[3][2].".<br>";
array("Saab",5,2),
array("Land Rover",17,15) ?>
);

58
Accessing Multidimensional Arrays elements:-
•Output:-

Volvo: In stock: 22, sold: 18.


BMW: In stock: 15, sold: 13.
Saab: In stock: 5, sold: 2.
Land Rover: In stock: 17, sold:
15.

59
Accessing Multidimensional Arrays elements:-
• We can use a for loop inside for ($row = 0; $row < 4; $row++)
another for loop to get element
from multidimensional array. {
<html> echo "<p><b>Row number
<body> $row</b></p>";
echo "<ul>";
<?php
for ($col = 0; $col < 3; $col++) {
$cars = array (
echo "<li>".$cars[$row][$col]."</li>";
array("Volvo",22,18),
}
array("BMW",15,13), echo "</ul>";
array("Saab",5,2), }
array("Land Rover",17,15) ?>
); </body> </html>
60
Accessing Multidimensional Arrays elements:-
• Output:- Row number 2
Row number 0 • Saab
• Volvo • 5
• 22 • 2
Row number 3
• 18
• Land Rover
Row number 1 • 17
• BMW • 15
• 15
• 13
61
Extracting Data from Arrays :-
• You can use extract() function extract($course);
to extract data from array and echo “CO=$CO<br>”;
store it in variables. echo “IT=$IT<br>”;
<html> echo “CE=$CE<br>”;
?>
<title> Array </title>
</body> </html>
<body>
<?php Output:
$course*“CO”+ = “Computer Engg.”; CO=Computer Engg.
$course*“IT”+ = “Information Tech.”; IT=Information Tech.
$course*“CE”+ = “Civil”; CE=Civil

62
Compact() Function:-
• This function is opposite of Example:-
extract() function. <?php
• It return an array with all the $var1=“PHP”;
variables added to it. $var2=“JAVA”;
• The compact() functions create $var3=compact(“var1”, “var2”);
associative array whose key print_r(var3);
value are the variable name ?>
and whose values are the
variable values. Output:-
Array( [var1]=> PHP [var2]=> JAVA)

63
Implode and Explode:-
• Imploding and Exploding are Syntax:-
couple of important functions string implode(separator, array);
of PHP that can be applied on
strings or arrays. • The implode() function accept
• The implode() is a built-in two parameter out of which one
function in PHP and is used to is optional and one is
join the element of an array.
mandatory.
• The implode function return a • Separator:-
string from the element of an
array.
• Array:-

64
Implode :-
• Example:- echo $text;
<html> ?>
</body>
<head>
</html>
<title> array </title>
<body> Output:-
<?php
$course[0] = “Computer Engg.”; Computer Engg., Information Tech.,
Civil
$course[1] = “Information Tech.”;
$course[2] = “Civil”;
$text=implode(“,”,$course);
65
Implode :-
• Example without separator:- // join without separator
<html> print_r(implode(“-”,$inputArray));
?>
<head>
</body>
<title> array </title> </html>
<body>
<?php Output:-
$inputArray= array(‘CO’, ‘IF’, ‘CE’);
COIFCE
// join without separator
CO-IF-CE
print_r(implode($inputArray));
print_r(“<BR>”);
66
Explode:-
• The explode() function break a
string into an array. • The implode() function accept
• The explode() is a built-in three parameter out of which
function in PHP is used to split one is optional and two is
a string in different string. mandatory.
• The explode() function split a • Separator:-
string based on the string
delimeter.
• Syntax:- • OrignalString:-
array explode(separator,
OrignalString, NoOfElements); • NoOfElements

67
Explode :-
• Example:- ?>
<html> </body>
</html>
<head>
<title> array </title> Output:-
<body>
Array ( [0]=> PHP: [1]=> Welcome
<?php
[2]=> to [3]=> the [4]=> world
$str= PHP: Welcome to the [5]=> of [6]=> PHP
world of PHP;
print_r(explode(“ ”,$str));

68
Array_flip() function :-
• The array_flip() function $a=array( “CO”=> “Computer Engg.”,
flip/exchange all key with their “IT” => “Information Tech.”, “CE” =>
associated value in an array. “Civil”);
• The array_flip() is a built-in $result=array_flip($a);
function in PHP is used to print_r($result);
exchange element within array.
?>
<html> </body>
<head> </html>
<title> array </title> Output:-
<body> Array ( [Computer Engg.]=> CO
<?php [Information Tech.]=> IT [Civil]=> CE)

69
Traversing Arrays:-
• Traversing an array means to foreach($course as $val) {
visit each and every element of echo $val “<br>”; -
array using a looping structure
and and iterator function . $total = count($course);
• There are several way to echo “The number of element
traverse array in PHP. are $total<br>”;
<?php echo “Looping using for:<br>”;
$course = array(“CO”, “IT”, for($n=0; $n<$total; $n++)
“CE”); {
echo “Looping using echo $course*$n+, “<br>”;
foreach:<br>”; }
?>
70
Traversing Arrays:-
• Output:- foreach($course as $val) {
Looping using foreach : echo $val “<br>”; -
CO $total = count($course);
IT echo “The number of element
CE are $total<br>”;
The number of elements are 5 echo “Looping using for:<br>”;
Looping using for : for($n=0; $n<$total; $n++)
CO {
IT echo $course*$n+, “<br>”;
CE }
?>
71
Modifying Data in Arrays:-
• Example:- echo $course*0+, “<br>”;
<html> echo $course[1], “<br>”;
<head> echo $course[2], “<br>”;
<title> Modifying in array </title> echo “After Modification <br>”;
<body> $course[1] = “Mechanical Engg.”;
<?php $course[] = “Electrical Engg.”;
$course*0+ = “Computer Engg.”; for($i=0; $i<count($course);$i++)
$course*1+ = “Information Tech.”; {
$course*2+ = “Civil”; echo $course*$i+, “<br>”;
echo “Before Modification”; }
?> </body></html>
72
Modifying Data in Arrays:-
• Output:-  Deleting Array Element:-
Before Modification • The unset() function is used to
Computer Engg. remove element from array.
Information Tech. • The unset() function is used to
Civil destroy any other variable and
After Modification same way use to delete any
Computer Engg. element of an array.
Mechanical Engg. • Syntax:-
Civil void unset($var,….);
Electrical Engg
73
Deleting Array Element:-
• Example 1:- unset($course[1]);
<?php echo “Before Deletion: <br>”;
$course = array(“CO”, “IT”, print_r($course);
“ME”, “CE”); echo “Delete entire array
echo “Before Deletion: <br>”; elements: <br>”;
unset($course[1]);
echo $course*0+, “<br>”;
?>
echo $course*1+, “<br>”; • Output:-
echo $course*2+, “<br>”; Array ([0]=> CO [2]=> ME [3]=> CE)
echo $course[3], “<br>”; Delete entire array elements:

74
Deleting Array Element:-
• Example 2:-
<?php echo “After Deletion: <br>”;
$course*0+ = “Computer Engg.”;
$course*1+ = “ ”;
$course*1+ = “Information Tech.”;
$course*2+ = “Civil”; for($i=0; $i<count($course);$i++)
$course[3] = “Electrical Engg.”; {
echo “Before Deletion: <br>”; echo $course*$i+, “<br>”;
echo $course*0+, “<br>”; }
echo $course*1+, “<br>”; ?>
echo $course*2+, “<br>”;
echo $course[3], “<br>”;

75
Deleting Array Element :-
• Output:-  Reducing an array:-
Before Deletion: • The array_reduce() function
Computer Engg. apply a user define function to
Information Tech. each element of an array, so as
Civil to reduce the array to a single
Electrical Engg. value.
After Deletion: • Syntax:-
Computer Engg. • Mixed array_reduce(array
Civil $array, callable $callback
Electrical Engg [, mixed $initial = null])

76
Reducing Array Element :-
• Example:-  Array_search:-
<?php • The array_search() function an
$n = array(1, 3, 5, 7); array for a value and return the
$total = array_reduce($n, key
‘add’); • Syntax:-
• Mixed array_reduce (mixed
echo $total;
$to_find, array $input [, bool
?> $strict = false])
• Output:- 16

77
Array_search :-
• Example:-
<?php
$a = array(“a”=> “5”, “b”=>
“7”, “c”=> “9”,);
echo array_search(7, $a, true);
?>
• Output:- b

78
Sorting Array :-
• Sorting refer to ordering data in • ksort() - sort associative arrays in
an alphanumerical, numerical
order and increasing or ascending order, according to
decreasing fashion. the key
• Sorting function for array in PHP • arsort() - sort associative arrays
• sort() - sort arrays in ascending in descending order, according
order to the value
• rsort() - sort arrays in descending • krsort() - sort associative arrays
order
in descending order, according
• asort() - sort associative arrays in
ascending order, according to the to the key
value

79
sort() and rsort() in Array :-
• Example:- echo “After sorting in Ascending
<?php order:<br>”;
$num = array(40, 61, 2, 22, 13); sort($num);
echo “Before sorting:<br>”; $arrlen=count($num);
for($x=0; $x<$arrlen; $x++)
$arrlen=count($num);
{
for($x=0; $x<$arrlen; $x++) echo $num*$x+, “<br>”;
{ }
echo $num[$x], “<br>”; echo “After sorting in Descending
} order:<br>”;

80
sort() and rsort() in Array :-
sort($num); • Output:-
$arrlen=count($num); Before sorting:-
40
for($x=0; $x<$arrlen; $x++) 61
2
{
22
echo $num*$x+, “<br>”; 13
After sorting in Ascending order:
} 2
?> 13
22
40
61

81
sort() and rsort() in Array :-
Output:-
After sorting in Descending
order:
61
40
22
13
2

82
aort() and ksort() in Array :-
• Example:- echo "<br>";
<?php }
$age = array("Peter"=>"35", echo “Sorting according to Key:<br>”;
"Ben"=>"37", "Joe"=>"43"); ksort($age);
echo “Sorting according to foreach($age as $x => $x_value)
Value:<br>”; {
asort($age); echo "Key=" . $x . ", Value=" .
foreach($age as $x => $x_value) $x_value;
{ echo "<br>";
echo "Key=" . $x . ", Value=" . }
$x_value; ?>

83
aort() and ksort() in Array :-
Output:-
Sorting according to Value:
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
Sorting according to Key:
Key=Ben, Value=37
Key=Joe, Value=43
Key=Peter, Value=35
84
Splitting and Merging Array :-
• You can also cut up and • You can also merge two or more
merge array when needed. array with array_mearge()
• Suppose you have 4 course in
array of course and you want
to get a subarray consisting of • Syntax:-
last 2 items.
• You can do this with array_merge(array1, array2,…..);
array_slice() function
• Syntax:-
array_slice(array, start, length,
preserve);

85
Splitting Array :-
• Example:- echo “After Spliting array: <br>”;
<?php subarray = array_slice($course, 1,
$course*0+ = “Computer Engg.”; 2);
$course*1+ = “Information Tech.”; foreach($subarray as $value)
$course*2+ = “Civil”; {
echo “Before Spliting array: <br>”; echo “Course: $value<br>”;
}
echo $course*0+, “<br>”;
?>
echo $course*1+, “<br>”;
echo $course*2+, “<br>”;

86
Splitting Array :-
• Output:-
Before Spliting array:
Computer Engg
Information Tech.
Civil
After Spliting array:
Course: Information Tech.
Course: Civil

87
Merging Array :-
• Example:- echo “Subject: $value<br>”;
<?php }
$sem5 = array(“ACN”, “OSY”, ?>
“SEN”); Output:-
$sem6 = array(“WPD”, “JAVA”, Subject: ACN
“Python”); Subject: OSY
$subject = array_merge($sem5, Subject: SEN
$sem6); Subject: WPD
foreach($subject as $value) { Subject: JAVA
Subject: Python

88
array_diff() & PHP Array functions:-
• Example:- • array_intersect():-
<?php • array_chunk():-
$a1 = array(“ACN”, “OSY”, • array_combine():-
“SEN”); • array_unique():-
$a2 = array(“ACN”, “JAVA”, • array_count_value()
“Python”); • array_pop():-
$diff = array_diff($a1, $a2); ?> • array_product():-
• array_push:-
Output:-
• array_reverse():-
Array ([1]=> OSY [2]=> Python) • array_sum():-

89
PHP Functions and its Types:-
• The real power of PHP comes • A function will be executed by a
from its functions. call to the function.
• PHP function are similar to • There a two part
other programming language.
1) Crate a PHP function
• A function is a piece of code
which take one or more input 2) calling a PHP function
of parameter and does some
processing and return a value. • User define function declaration
• PHP has more than 1000 start with word function:
built-in functions, and in
addition you can create your
own custom functions.
90
PHP Functions and its Types:-
• Syntax:- <body>
function functionName() <?php>
{ function writeMessage()
code to be executed; {
} echo “Welcome to PHP function!”;
• Example:- }
<html> writeMessage();
<head> ?> </body> </html>
<title> PHP function Program Output:-
</title> </head> Welcome to PHP function!

91
PHP Functions with Parameters:-
• PHP gives you option to pass function add($num1, $num2)
your parameters inside a {
function.
$sum = $num1+ $num2;
• Example 1:-
echo “Sum of two number is:
<html>
$sum”;
<head> }
<title> PHP function with add(70,40);
parameter </title> </head>
?> </body> </html>
<body>
Output:-
<?php>
Sum of two number is: 110

92
PHP Functions with Parameters:-
• Example 2:- familyName(“Ram","1985");
<html> familyName(“Laxman","1988");
<head> familyName(“Sita","1990");
<body> ?>
<?php </body> </html>
function familyName($fname,
$year) { Output:-
echo “Name $fname Born in Name: Ram Born in 1985
$year <br>"; Name: Laxman Born in 1988
} Name: Sita Born in 1990

93
PHP Functions returning value:-
• A function can return a value {
using the return statement in $sum = $num1+ $num2;
conjunction with a value or return $sum”;
object. }
• You can return more than one $return_value = add(70,40);
value from a function using echo “Returned value from the
return array (1,2,3,4).
function: $return_value”;
• Example:- ?>
<?php> Output:-
function add($num1, $num2) Returned value from the function: 110

94
Variable Functions:-
• PHP support the concept echo “In simple()<br/>”;
variable function. }
• Means that if variable name is function data($arg =“”) ,
parentheses appended to it, echo “In data(); argument was
PHP will look for a function ‘$arg’.</br>”;
with same name. }
$func = ‘simple’;
• Example:- $func();
<?php> $func = ‘data’;
function simple() $func(‘test’) ?>
Output:-
{
In Simple()
In data(); argument was ‘test’. 95
Anonymous Functions (Lambda Function):-
• We can define a function that $r = $add(2, 3);
has no specified name. such a
function is Anonymous echo $r;
Functions or Lambda Funcion. ?>
• Use as a values of callback. Output:-
• The function is randomly 5
generated and returned.
• Example 1:-
<?php>
$add= creare_function( ‘$a’, ‘$b’,
‘return($a+$b)’);

96
Anonymous Functions (Lambda Function):-
• Example 2:- ?>
<?php> Output:-
$gpg= function($name); Welcome To GPG
{ Welcome To Computer Dept.
printf(“\nWelcome To”, $name);
};
$gpg(‘GPG’);
echo”<br>”;
$gpg(‘Computer Dept. ’);
97
Operation on String:-
• PHP string is a sequence of • But the assignment must surround
characters i.e. used to store the string with quote mark (“…” or
and manipulate text . ‘…’)
• String is one of the data type  Single quoted string:-
supported by PHP. <?php
• The string variable can $name = ‘Ram’;
contain alphanumerical $str = ‘Hello $name’;
characters. echo $str “br>”;
• A “string” of text can be var_dump(‘Hello Ram’);
stored in a variable in much ?>
the same way as a numerical Output: Hello $name
value. string(9) Hello Ram
98
Operation on String:-
 Double quoted string:-
<?php
$name = ‘Ram’;
$str = “Hello $name”;
echo $str;
?>
Output: Hello Ram

99
Converting to and from Strings:-
 Using number_format():- // convert string in number
• The number_format() function echo number_format($num,3);
is used to convert string into a ?>
number.
<?php Output: 2021
$num = “2021.0429”; 2021.042
//convert string in number
echo number_format($num),
“<br>”;

100
Converting to and from Strings:-
 Using type casting:-
• Typecasting can directly // Type cast using float
convert a string into float, echo (float)$num, “<br>”;
double and integer primitive // Type cast using double
type. echo (double)$num;
<?php ?>
$num = “2021.0429”;
//Type cast using int Output: 2021
echo (int)$num, “<br>”; 2021.0429
2021.0429

101
Converting to and from Strings:-
 Using intval() and floatval:-
• The intval() and floatval() // intval() convert string into float
function also convert a string echo floatval($num);
into its corresponding integer ?>
and float value.
<?php Output: 2021
$num = “2021.0429”; 2021.0429
//intval() convert string into int
echo intval($num), “<br>”;

102
Type Specifier :-
• %: To display %. • u: display as an unsigned
• b: display in Binary number. decimal number.
• c: display as the corresponding • x: display as a hexadecimal
ASCII character. number.
• d: display as a decimal number.
• e: for Scientific notation
• f: display as a real number.
• o: display as a octal number.
• s: display as a string.

103
Type Specifier:-
• Example:- $m= 04;
<?php> $date= 29;
printf(“ I have %s pens and %s echo “The date is:”;
pencils. <br>”, 3, 12); printf(“%02d-%02d-%04d <br>”,
$date, $m, $y);
$str=sprintf(“ After using I have ?>
%s pens and %s pencils.<br>”, 2,
10); Output:-
I have 3 pens and 12 pencils.
echo $str, “<br>”; After using I have 2 pens and 10 pencils.
$y=2021; The date is: 29-04-2021

104
PHP String Functions:-

105
PHP String Functions:-

106
PHP String Functions:-

107
PHP String Functions:-

strcomp()

108
PHP String Functions:-

trim($str)

109
PHP String Functions:-

ltrim($str)

110
PHP Math Functions:-

111
PHP Math Functions :-

112
PHP Math Functions :-

113
PHP Math Functions :-

114
PHP Math Functions :-

115
Round():-
• This function take numerical Example:-
value as argument and return • round(1.75572,2) = 1.76
the highest integer value by • round(2341757, -3)= 234200
rounding up value. • round(7.5, 0,
PHP_ROUND_HALF_UP)= 8
• round(7.5, 0,
• PHP_ROUND_HALF_UP: PHP_ROUND_HALF_DOWN)= 7
• PHP_ROUND_HALF_DOWN: • round(7.5, 0,
• PHP_ROUND_HALF_EVEN: PHP_ROUND_HALF_EVEN)= 8
• round(7.5, 0,
• PHP_ROUND_HALF_ODD: PHP_ROUND_HALF_ODD)= 7

116
PHP Date Function:-
• PHP Date function is an In-built Example:-
function that works date data <?php
type. echo “Today’s Date is:”;
• The PHP date function is used $today = date(“d/m/Y”);
to format a date or time into a echo $today;
human readable format. ?>
• Syntax:- • Output:-
date(format, timestamp); Today’s Date is: 01/04/2021

117
Get a Date:-
• Here are some characters that Example:-
are commonly used for dates: <?php
echo "Today is " . date("Y/m/d") . "<br>";
• d - Represents the day of the echo "Today is " . date("Y.m.d") . "<br>";
month (01 to 31) echo "Today is " . date("Y-m-d") . "<br>";
• m - Represents a month (01 to echo "Today is " . date("l");
12) ?>
• Y - Represents a year (in four • Output:-
digits) Today is 2020/11/03
Today is 2020.11.03
• l (lowercase 'L') - Represents
the day of the week Today is 2020-11-03
Today is Tuesday
118
Get a Time:-
• Here are some characters that Example:-
are commonly used for times:
<?php
echo "The time is " . date("h:i:sa");
• H - 24-hour format of an hour (00
to 23) ?>
• h - 12-hour format of an hour • Output:-
with leading zeros (01 to 12) The time is 07:50:27am
• i - Minutes with leading zeros (00
to 59)
• s - Seconds with leading zeros (00
to 59)
• a - Lowercase Ante meridiem and
Post meridiem (am or pm)
119
Get Your Time Zone:-
• Example:- • Create a Date With mktime():-
<?php • Syntax:-
date_default_timezone_set("Americ mktime(hour, minute, second, month,
a/New_York"); day, year)
echo "The time is " . date("h:i:sa"); • Example:-
?> <?php
Output:- $d=mktime(03, 14, 54, 04, 01, 2021);
The time is 03:40:15pm echo "Created date is " . date("Y-m-d
h:i:sa", $d); ?>
Output:- Created date is 2021-04-01
03:14:54pm

120
Basic Graphics Concept:-
• PHP support basic computer • Creating an Image:-
graphics. An image is a • The imagecreate() function is used to
rectangle of pixels of various create a new image.
colors. • Syntax:-
• Computer usually create color imagecreate(x_size, y_size);
using a color theory model • x_size and y_size parameter are in
called RGB model. pixel.
• The three basic color that are • Example:-
combine to create the colors $img_height= 200;
that we see on the computer $img_width= 400;
display. $img= imagecreate($img_height,
$img_width);
121
Basic Graphics Concept:-
• It is preferred to use • You can pass RGB value on
imagecreatetruecolor() to imagecolorallocate() to set color.
create a image instead of • If you want solid red the you had
imagecreate(). pass red value 0-255 and blue
• Because the image processing and green value 0.
occurs on the highest quality
image possible which can be $bg_color= imagecolorallocate($img,
create using 200, 0, 0);
imagecreatetruecolor() .
• To set a colors to be used in
image use imagecolorallocate()
122
Basic Graphics Concept:-
• To send JPEG image back to • Example1:-
browser, you have to tell the <?php
Brower you are doing so with
the header function to set the $img_height= 200;
image type. $img_width= 400;
• You sent the image with the $img= imagecreate($img_height,
imagejpeg() function. $img_width);
$bg_color= imagecolorallocate($img,
• Imagegif():-
200, 0, 0);
• imagejpeg() header(‘Content-Type:image/jpeg);
• Imagewbmp():- imagejpeg($img);
• Imagepng():- ?>

123
Create Image:-
• Example1:- imagedestroy($im);
<?php print "<img
$img_height= 200; src=image.png?".date("U").">";
$img_width= 400; ?>
$img=
@imagecreate($img_height,
$img_width);
$bg_color=
imagecolorallocate($img, 255, 0,
0);
imagepng($im,"image.png");

124
Draw Line on Image:-

125
Draw Line on Image:-
• <?php
$im = @imagecreate(200, 200);
$background_color = imagecolorallocate($im, 255, 255, 0); // yellow
$red = imagecolorallocate($im, 255, 0, 0); // red
$blue = imagecolorallocate($im, 0, 0, 255); // blue
imageline ($im, 5, 5, 195, 5, $red);
imageline ($im, 5, 5, 195, 195, $blue);
imagepng($im,"image.png");
imagedestroy($im);
print "<img src=image.png?".date("U").">";
?>

126
Draw Rectangles on Image:-
X1
Y1 Y2

X2

127
Draw Rectangles on Image :-
• <?php
$im = @imagecreate(200, 200);
$background_color = imagecolorallocate($im, 255, 255, 0); // yellow
$red = imagecolorallocate($im, 255, 0, 0); // red
$blue = imagecolorallocate($im, 0, 0, 255); // blue
imagerectangle ($im, 5, 10, 195, 50, $red);
imagefilledrectangle ($im, 5, 100, 195, 140, $blue);
imagepng($im,"image.png");
imagedestroy($im);
print "<img src=image.png?".date("U").">";
?>

128
Draw Ellipses on Image:-

129
Draw Ellipses on Image :-
• <?php
$im = @imagecreate(200, 200);
$background_color = imagecolorallocate($im, 255, 255, 0); // yellow
$red = imagecolorallocate($im, 255, 0, 0); // red
$blue = imagecolorallocate($im, 0, 0, 255); // blue
imageellipse($im, 50, 50, 40, 60, $red);
imagefilledellipse($im, 150, 150, 60, 40, $blue);
imagepng($im,"image.png");
imagedestroy($im);
print "<img src=image.png?".date("U").">";
?>

130
Draw Arc on Image:-

131
Draw Arc on Image :-
• <?php
$im = @imagecreate(200, 200);
$background_color = imagecolorallocate($im, 255, 255, 0); // yellow
$red = imagecolorallocate($im, 255, 0, 0); // red
$blue = imagecolorallocate($im, 0, 0, 255); // blue
imagearc($im, 20, 50, 40, 60, 0, 90, $red);
imagearc($im, 70, 50, 40, 60, 0, 180, $red);
imagefilledarc($im, 20, 150, 40, 60, 0, 90, $blue, IMG_ARC_PIE);
imagefilledarc($im, 70, 150, 40, 60, 0, 180, $blue, IMG_ARC_PIE);
imagepng($im,"image.png");
imagedestroy($im);
print "<img src=image.png?".date("U").">";
?>

132
Image with text:-
• The imagestring() function is an • Example:- png.php file name
inbuilt function in PHP which is <?php
used to draw the string header(‘Content-Type:image/jpeg);
horizontally. $img= imagecreate(150, 50);
• This function draw the string at $bg_color= imagecolorallocate($img,
given position. 220, 230, 140);
$txt_color= imagecolorallocate($img,
• Syntax:- 0, 0, 0);
Imagestring( $image, $font, $x, Imagestring( $img, 5, 6, 17, “Welcome
$y, $string, $color); to GPG”, $txt_color);
imagepng($img);
?>
133
Image with text :-
• <?php;
$im = @imagecreate(200, 200)
$background_color = ima, 50, "Hello !", gecolorallocate($im, 255, 255, 0); // yellow
$red = imagecolorallocate($im, 255, 0, 0); // red
imagestring($im, 5, 10, "Hello !", $red);
imagestring($im, 2, 5$red);
imagestring($im, 3, 5, 90, "Hello !", $red);
imagestring($im, 4, 5, 130, "Hello !", $red);
imagestring($im, 5, 5, 170, "Hello !", $red);
imagestringup($im, 5, 140, 150, "Hello !", $red);
imagepng($im,"image.png");
imagedestroy($im);
print "<img src=image.png?".date("U").">";
?>
134
Resize Image:-

135
Resize Image:-
• <?php;
$original_image = imagecreatefrompng("image.png");
$image_info = getimagesize("image.png");
$width = $image_info[0]; // width of the image
$height = $image_info[1]; // height of the image
$new_width = round ($width*0.7);
$new_height = round ($height*0.7);
$new_image = imagecreate($new_width, $new_height);
imagecopyresized($new_image, $original_image, 0, 0, 0, 0, $new_width, $new_height,
$width, $height);
imagepng($new_image,"resized_image.png");
imagedestroy($new_image);
print "<img src=image.png?".date("U").">";
?>
136
Displaying Image in HTML page:-
• If you had a PNG on the server, • Example:-
abc.png, you could display it <html>
this way in a web using HTML. <head>
<img src= “abc.png”> <title> Embedding created image in
HTML page </title>
</head>
• In the same way you can give <body>
the name of the script that <h2> PNG image create using script
generate the png image </h2> <br>
<img src= “png.php”> <img src= “png.php”>
</body> </html>

137
Creation of PDF Document:-
• FPDF is a PHP class which  Choice of measure unit, page
allows generating PDF file with format and margins.
pure PHP that is to say without  Page header and footer format.
using a PDFlib library.  Automatic line break and text
• F from FPDF stand for free. justification.
• We may use it for any kind of  Image format (JPEG, GIF, and
usage and modify it to suite we PNG)
need.  Color and line.
• Features of FPDF:-  Page compression.
Automatic page break.
138
Cell():-

‘http://www.gpgondia.ac.in’

139
Creation of PDF Document :-
<?php
require(‘fpdf.php’);
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont(‘Arial’, ‘B’, 16);
$pdf->Cell(80, 10, ‘Welcome to online class’);
$pdf->Output(‘my_pdf.pdf’, ‘I’);

?>
140
Adding border , alignment, color , link in PDF Document :-
<?php
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(80,10,‘Welcome to
GPG!',1,0,'R',false,'https://www.gpgondia.ac.in.com');
$pdf->Output(‘gpg.pdf','I'); // send to browser and display
?>
141
Adding background color in PDF Document :-
<?php
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->SetFillColor(1,255,255);
$pdf->Cell(80,10,‘Welcome to
GPG!',1,0,'R',false,'https://www.gpgondia.ac.in.com');
$pdf->Output(‘gpg.pdf','I'); // send to browser and display
?>
142
Adding font colour by SetTextColor() in PDF Document :-
<?php
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->SetFillColor(1,255,255);
$pdf->SetTextColor(255,254,254);
$pdf->Cell(80,10,‘Welcome to
GPG!',1,0,'R',false,'https://www.gpgondia.ac.in.com');
$pdf->Output(‘gpg.pdf','I'); // send to browser and display
?>
143
Saving the PDF Document :-
• $pdf->Output('my_file.pdf','I'); // Send to browser and display

• $pdf->Output('my_file.pdf','D'); // Force file download with


name given ( name can be changed )

• $pdf->Output('my_file.pdf','F'); // Saved in local computer


with the file name given

• $pdf->Output('my_file.pdf','S'); // Return the document as a


string.
144

You might also like