0% found this document useful (0 votes)
11 views92 pages

WBP Unit 2

The document provides an overview of PHP arrays, detailing their types (indexed, associative, and multidimensional) and various functions for manipulating them. It explains how to create, access, and loop through elements in these arrays, as well as functions like extract, compact, implode, explode, and array_flip. Additionally, it covers sorting functions for arrays, demonstrating how to sort both indexed and associative arrays in ascending and descending order.

Uploaded by

pagareankita29
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views92 pages

WBP Unit 2

The document provides an overview of PHP arrays, detailing their types (indexed, associative, and multidimensional) and various functions for manipulating them. It explains how to create, access, and loop through elements in these arrays, as well as functions like extract, compact, implode, explode, and array_flip. Additionally, it covers sorting functions for arrays, demonstrating how to sort both indexed and associative arrays in ascending and descending order.

Uploaded by

pagareankita29
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 92

UNIT 2

Arrays, Functions and Graphics


PHP Arrays
• An array stores multiple values in one single variable
• An array is a special variable that can hold many values under a single name, and
we can access the values by referring to an index number or key name.

• Advantage of PHP Array


• Less Code: We don't need to define multiple variables.
• Easy to traverse: By the help of single loop, we can traverse all the elements of an
array.
• Sorting: We can sort the elements of array.
PHP Arrays
• Types of Array in PHP:
• There are 3 types of array in PHP.

1. Indexed Array -Arrays with a numeric index


2. Associative Array -Arrays with named keys
3. Multidimensional Array-Arrays containing one or more arrays
Indexed Array
• An array with a numeric index where elements are stored linearly and are accessed
using index number, by default the first element has index number 0, the second
element has index number 1 and so on.
• There are two ways to define indexed array:

• 1st way (with array function):


• Syntax: $array_name=array(value1, value2, value3, …)
• Example:
• $student=array("raj","ram","sagar");

• 2nd way(without array function):


• Syntax: $array_name[index_number]=value;
• Example:
• $student[0]=“raj";
• $student[1]=“ram";
• $student[2]=“sagar";
Indexed Array

Example:
Create an indexed array named $student, assign three elements to it, and
then print a text containing the array values:

<?php
$student=array("raj","ram","sagar");
echo "student names are: $student[0], $student[1],and $student[2] <br>";
?>
Indexed Array
Example: To loop through and print all the values of an indexed array, we can use a foreach loop or for loop, like this:
<?php
Output:
//First method to create an indexed array Accessing elements of indexed array directly:
$student=array("raj","ram","sagar"); student names are: raj, ram,and sagar
//Second method to create an indexed array looping through elements of indexed array using for-each loop:
student name:raj
//$student[0]="raj"; student name:ram
//$student[1]="ram"; student name:sagar
//$student[2]="sagar"; looping through elements of indexed array using for loop:
student name: raj
//Accessing elements of indexed array directly
student name: ram
echo "Accessing elements of indexed array directly:<br>"; student name: sagar
echo "student names are: $student[0], $student[1],and $student[2] <br>";

//Accessing elements of indexed array using for-each loop


echo "looping through elements of indexed array using for-each loop:";
foreach($student as $x){
echo "<br> student name:$x ";
}
//Accessing elements of indexed array using for loop
echo “<br>looping through elements of indexed array using for loop:";
for($i=0;$i<count($student);$i++){
echo "<br>student name: $student[$i]";
}
?>
Associative Array
• Associative arrays are used to store key value pairs and behave more like two column table
where the first column is the key and the second column is the value.
• The elements of an associative array can only be accessed or changed by the
corresponding key names
• In PHP, the "=>" symbol is used to establish association between a key and its value.
• There are two ways to define associative array:

• 1st way (with array function):


• Syntax: $array_name=array(key=>value,key=>value,key=>value,etc.)
• Example:
• $student=array("name"=>"raj","age"=>"25","email"=>"[email protected]");

• 2nd way(without array function):


• Syntax: Syntax: $array_name[key]=value;
• Example:
• $student["name"]="raj";
• $student["age"]="25";
• $student["email"]="[email protected]";
Associative Array
Example:
Create an associative array named $student, assign three elements to it, and then print a
text containing the array values:

<?php
$student=array("name"=>"raj", "age"=>"25","email"=>"[email protected]");
echo ("<br>name of student:" .$student["name"]);
echo ("<br>age of student :" .$student["age"]);
echo ("<br>email of student:".$student["email"]);
?>
Associative Array
Example: To loop through and print all the values of an associative array, we can use a foreach loop or foor loop , like this:
<?php
//First method to create an associate array
$student=array("name"=>"raj","age"=>"25","email"=>"[email protected]");
//Second method to create an associate array
//$student["name"]="raj";
//$student["age"]="25";
//$student["email"]="[email protected]";

//Accessing the elements of associative-array directly


echo "<br>Accessing the elements of associative-array directly";
echo "<br>name of student:" .$student["name"];
echo "<br>age of student :" .$student["age"];
echo "<br>email of student:".$student["email"];

//Accessing the elements of associative-array using for-each loop


echo "<br>looping through the elements of associative-array using for-each loop";
foreach($student as $x=>$y){
echo "<br>$x: $y ";
}
Output:
Accessing the elements of associative-array directly
//Accessing the elements of associative-array using for loop
name of student:raj
echo "<br>looping through the elements of associative-array using for loop"; age of student :25
$keys = array_keys($student); email of student:[email protected]
$values = array_values($student); looping through the elements of associative-array using for-each loop
for($i = 0;$i < count($student);$i++) { name: raj
age: 25
echo "<br> $keys[$i] : $values[$i] ";
email: [email protected]
} looping through the elements of associative-array using for loop
?> name : raj
age : 25
email : [email protected]
Multidimensional Array
• PHP multidimensional array is also known as array of arrays.
• A multidimensional array is an array containing one or more arrays and can be accessed via multiple
indices.
• A multidimensional array in PHP can have two or more dimensions
• For a two-dimensional array we need two indices to select an element
• For a three-dimensional array we need three indices to select an element
• It allows you to store tabular data in an array and it can be represented in the form of matrix which
is represented by row * column.

• Syntax for creating multidimensional array in php:


• $array_name=array(
array(elements,….),
array(elements,….),

);
• Example:
• $student = array (array("raj",3101,95),
• array("ram",3102,96),
Multidimensional Array
Example:
<?php
//creating a multidimensional array
$student = array (array("raj",3101,95),
array("ram",3102,96),
array("Sagar",3102,97));
// Accessing the elements directly
echo "<br>name: ".$student[0][0]." rollno: ".$student[0][1]." percentage: ".$student[0][2];
echo "<br>name: ".$student[1][0]." rollno: ".$student[1][1]." percentage: ".$student[1][2];
echo "<br>name: ".$student[2][0]." rollno: ".$student[2][1]." percentage: ".$student[2][2];
?>

Output:
name: raj rollno: 3101 percentage: 95
name: ram rollno: 3102 percentage: 96
name: Sagar rollno: 3102 percentage: 97
Multidimensional Array
Example:
<?php
//creating a multidimensional array
$student = array (array("raj",3101,95),
array("ram",3102,96),
array("Sagar",3102,97));

// Accessing the elements using nested for loop


for ($row = 0; $row < 3; $row++) {
for ($col = 0; $col < 3; $col++) {
echo $student[$row][$col]." ";
}
echo "<br>";
}
?>
Output:
• raj 3101 95
ram 3102 96
Multidimensional Array
Example:
<?php Output:
0: raj
//creating a multidimensional array 1: 3101
$student = array (array("raj",3101,95), 2: 95
array("ram",3102,96), 0: ram
array("Sagar",3102,97)); 1: 3102
2: 96

// Accessing the elements using for-each loop 0: Sagar


1: 3102
for ($i = 0; $i<count($student); $i++) {
2: 97
foreach ($student[$i] as $x=>$y) {
echo "$x: $y <br>";
}
echo "<br>";
}
Extracting Data from Arrays

1. Extract()
2. Compact()
3. Implode()
4. Explode()
5. Array_flip()
Extract() function
• The extract function extracts data from array and stores it in variable
• It converts associative array into variables (i.e. it converts array key into variable
names and array values into variable values).
• Syntax : extract($input_array)
• Example: Assign the values “Red",“Green“ and “Blue" to the variables $a, $b and $c
<?php
$colors = array("a" => "Red", "b" => "Green", "c" => "Blue");
extract ($colors);
echo "\$a = $a; \$b = $b; \$c = $c";
?>
• Output:
• $a = Red; $b = Green; $c = Blue
Compact() function
• The compact() function is opposite of extract() function
• The compact() function creates an associative array from variables and their values
• Syntax: compact(var1, var2,…)
• Example:
<?php
$a= "Red";
$b= "Green";
$c= "Blue";
$colors = compact("a","b","c");
print_r ($colors);
?>
• Output:
• Array ( [a] => Red [b] => Green [c] => Blue )
Implode() function
• The Implode() function is used to join elements of an array into a single string.(i.e it
converts an array into a string)

• Syntax: implode(separator, array)


• separator – optional, specifies what to put between array elements, default is “ ”
• array – The array whose value is to be joined to form a string
• Example:
<?php
$my_array = array('Hello','World!','Beautiful','Day!');
echo (implode(" ",$my_array)."<br>");
echo(implode("-",$my_array)."<br>");
?>
• Output:
• Hello World! Beautiful Day!
Hello-World!-Beautiful-Day!
Explode() function
• The explode() function breaks a string into an array.(i.e it converts a string into an array)
• Syntax: explode(separator, original string, no. of elements)
• separator- required, specifies where to break the string.
• original string - required, original string which is to be split into array.
• no. of elements -optional, specifies number of array elements to return.
• possible values are:
• positive- returns an array with maximum number of elements.
• negative- returns an array except of last n elements.
• zero- returns an array with one element(i.e whole string).
• Example:
<?php
$str = "Hello World! it's a beautiful day";
print_r (explode(" ", $str, 4));
echo "<br>";
print_r (explode(" ", $str,-2));
echo "<br>";
print_r (explode(" ", $str,0));
?>
• Output:
• Array ( [0] => Hello [1] => World! [2] => it's [3] => a beautiful day )
Array_flip() function

• The array_flip() function flips/ exchanges all keys with their associative values in an
array.
• Syntax: array_flip(array)
• array- specifies an array of key/value pairs to be flipped.
• Example:
<?php
$colors=array("a"=>"Red", "b"=> "Green", "c"=>"Blue");
print_r (array_flip($colors));
?>
• Output
• Array ( [Red] => a [Green] => b [Blue] => c )
Sorting Arrays
• The elements in an array can be sorted in alphabetical or numerical order, ascending
or descending.

• Sort Functions For Arrays:


1. sort() - sort arrays in ascending order
2. rsort() - sort arrays in descending order
3. asort() - sort associative arrays in ascending order, according to the value
4. ksort() - sort associative arrays in ascending order, according to the key
5. arsort() - sort associative arrays in descending order, according to the value
6. krsort() - sort associative arrays in descending order, according to the key
sort() function
Example: sort an array in ascending order
<?php
$num = array(4, 6, 2, 22, 11);
sort($num);
echo "<br> After sorting array elements in ascending order:<br>";
foreach($num as $x){
echo $x."<br>";
}
?>

Output:
• After sorting array elements in ascending order:
2
4
6
11
22
rsort() function
Example: sort an array in descending order
<?php
$num = array(4, 6, 2, 22, 11);
rsort($num);
echo "<br> After sorting array elements in descending order:<br>";
foreach($num as $x){
echo $x."<br>";
}
?>

Output:
• After sorting array elements in descending order:
22
11
6
4
2
asort() function

Example :sort associative arrays in ascending order, according to the value


<?php
$age = array("Raj"=>"22", "Ram"=>"42", "Yash"=>"35");
asort($age);
echo "After sorting associative arrays in ascending order, according to the
value:<br>";
foreach($age as $x => $y){
echo "Key=$x Value=$y <br>";
}
?>

Output:
After sorting associative arrays in ascending order, according to the value:
Key=Raj Value=22
Key=Yash Value=35
Key=Ram Value=42
ksort() function
Example: sort associative arrays in ascending order, according to the key
<?php
$age = array("Raj"=>"22", "Ram"=>"42", "Yash"=>"35");
ksort($age);
echo "After sorting associative arrays in ascending order, according to the key:<br>";
foreach($age as $x => $y){
echo "Key=$x Value=$y <br>";
}
?>

Output:
After sorting associative arrays in ascending order, according to the key:
Key=Raj Value=22
Key=Ram Value=42
Key=Yash Value=35
arsort() function
Example : sort associative arrays in descending order, according to the value
<?php
$age = array("Raj"=>"22", "Ram"=>"42", "Yash"=>"35");
arsort($age);
echo "After sorting associative arrays in descending order, according to the value:<br>";
foreach($age as $x => $y){
echo "Key=$x Value=$y <br>";
}
?>

Output:
After sorting associative arrays in descending order, according to the value:
Key=Ram Value=42
Key=Yash Value=35
Key=Raj Value=22
krsort() function
Example : sort associative arrays in descending order, according to the key
<?php
$age = array("Raj"=>"22", "Ram"=>"42", "Yash"=>"35");
krsort($age);
echo "After sorting associative arrays in descending order, according to the key:<br>";
foreach($age as $x => $y){
echo "Key=$x Value=$y <br>";
}
?>

Output:
After sorting associative arrays in descending order, according to the key:
Key=Yash Value=35
Key=Ram Value=42
Key=Raj Value=22
Traversing arrays
• Traversing an array means accessing and processing each element in an array.
• We can loop through(traverse) an array in two ways:
1. using for each loop
2. using for loop
Traversing Indexed Array
Example: To loop through and print all the values of an indexed array, we can use a foreach loop or for loop, like this:
<?php
$student=array("raj","ram","sagar");

echo "<br>Looping through elements of indexed array using for-each loop";


foreach($student as $x){
echo "<br> student name:$x ";
}
echo "<br>Looping through elements of indexed array using for loop";
for($i=0;$i<count($student);$i++){
echo "<br>student name: $student[$i]";
}
?>
Output:
Looping through elements of indexed array using for-each loop
student name:raj
student name:ram
student name:sagar
Looping through elements of indexed array using for loop
student name: raj
student name: ram
student name: sagar
Traversing Associative Array
Example: To loop through and print all the values of an associative array, we can use a foreach loop or for loop, like this:
<?php
$student=array("name"=>"raj","age"=>"25","email"=>"[email protected]");
echo "looping through the elements of associative-array using for-each loop";
foreach($student as $x=>$y){
echo "<br>$x: $y ";
}
echo "looping through the elements of associative-array using for loop";
$keys = array_keys($student);
$values = array_values($student);

for($i = 0;$i < count($student);$i++) {


echo "<br> $keys[$i] : $values[$i] ";
}
?>
Output:

looping through the elements of associative-array using for-each loop


name: raj
age: 25
email: [email protected] looping through the elements of associative-array using for loop
name : raj
age : 25
email : [email protected]
Modifying Data in Array
Refer to the array and its index and then change that index’s value with another value.
Example:
<?php
$colors=array("Red","Green","Blue");
echo "<br> Before modifying elements in an array <br>";
print_r($colors);
$colors[0]="Orange"; //change the value of the first element in the array

echo "<br> After modifying elements in an array<br>";


print_r($colors);
?>

• Output
• Before modifying elements in an array
Array ( [0] => Red [1] => Green [2] => Blue )
After modifying elements in an array
Array ( [0] => Orange [1] => Green [2] => Blue )
Deleting Array Elements
• The unset() function is used to remove elements from the array
• Example:
<?php
$colors=array("Red","Green","Blue");
echo "<br> Before deleting elements in array<br>";
print_r($colors);
unset($colors[0]); //delete the value of the first element in the array

echo "<br> After deleting elements in array<br>";


print_r($colors);
?>
• Output
Before deleting elements in array
Array ( [0] => Red [1] => Green [2] => Blue )
After deleting elements in array
Array ( [1] => Green [2] => Blue )
Array_values() Function:
• The array_values() function returns all values from array and indexes the array
numerically.
• Syntax: array_values(array)
• Array - Required. Specifying an array
• Example:
<?php
$student=array("name"=>"raj","age"=>"25","email"=>"[email protected]");
print_r(array_values($student)); //Return all the values of an array (not the keys)
?>
• Output:
• Array ( [0] => raj [1] => 25 [2] => [email protected] )
Splitting Arrays
• The array_slice() function returns selected parts of an array. or
• The array_slice() function is used to extract a slice(part) of an array
• If the array have string keys, the returned array will always preserve the keys.
• Syntax: array_slice(array, start, length, preserve)
• array -Required. Specifies an array
• start -Required. Specifies the starting position of the slice in the array.
• If this value is set to is negative number, then the function starts slicing from the end of the array,
i.e., -1 refers to the last element of the array.
• length -Optional. Specifies the length of the slice.
• If this value is set to a negative number, the function will stop slicing that many elements from the
end of the array.
• If this value is not set, the function will return all elements, starting from the position set by the
start-parameter.
• Preserve- Optional. Specifies if the function should preserve or reset the keys. Possible values are:
• true - Preserve keys
• false - Default. Reset keys
Splitting Arrays
Example:
<?php
$colors=array("red","green","blue","yellow","brown");
echo "origional array<br/>";
print_r($colors);
echo "<br>";
echo "array after Splitting <br/>";
print_r(array_slice($colors,2,2,true));// Preserve keys
echo "<br>";
print_r(array_slice($colors,1,-2));/*Start the slice from the second element(i.e. 1st index
element), and stop slicing at 2 element from the end of the array*/
echo "<br>";
print_r(array_slice($colors,-2,1));//Start the slice from the second last element of array
?>
Output:
origional array
Array ( [0] => red [1] => green [2] => blue [3] => yellow [4] => brown )
array after Splitting
Array ( [2] => blue [3] => yellow )
Array ( [0] => green [1] => blue )
Merging Arrays
• The array_merge() function merges one or more arrays into a single array.

• Syntax: array_merge(array1, array2, array3, ...)

• Example : Merge two indexed arrays into a single array


<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r (array_merge($a1,$a2));//merge two indexed arrays into a single array
?>
• Output:
• Array ( [0] => red [1] => green [2] => blue [3] => yellow )
Merging Arrays

• Example : Merge two associative arrays into a single array


<?php
$a1=array("a"=>"red","b"=>"green");
$a2=array("c"=>"blue","b"=>"yellow");
print_r(array_merge($a1,$a2));//merge two associative arrays into a single array
?>

Note: If two or more array elements have the same key, the last one overrides the
others.

Output:
• Array ( [a] => red [b] => yellow [c] => blue )
String functions
• str_word_count() :
• The str_word_count() function counts the number of words in a string.

• Syntax: str_word_count(string)
• String: Required parameter. Specifies the string to check

• Example:
<?php
echo str_word_count("Hello world!");
?>
Output:
• 2
String functions
• strlen() :
• The strlen() function returns the length of a string(in bytes) including all the
whitespaces and special characters

• Syntax: strlen(string)
• String: Required parameter. Specifies the string to check

• Example:
<?php
echo strlen("Hello World!");
?>
Output:
• 12
String functions
• strrev() :
• The strrev() function is used to reverse a string
• Syntax: strrev(string)
• String: Required parameter . Specifies the string to reverse

• Example:
<?php
echo strrev("Hello World!");
?>
Output:
• !dlroW olleH
String functions
• strpos() :
• The strpos() function finds the position of the first occurrence of a substring inside another string.

• Syntax: strpos(origional_string , search_string , start)


• origional_String: Required parameter. Specifies the original string in which we need to search the
substring.
• search_string :Required parameter . Specifies the substring that we need to search in the original string.
• Start: Optional parameter . Specifies where to begin the search. If start is a negative number, it counts
from the end of the string

• Example:
<?php
echo strpos("I am a PHP programmer", "am");
echo "<br>";
echo strpos("I am a PHP programmer", "am",5);
?>
Output:
• 2
• 16
String functions
• str_replace():
• The str_replace() function replaces some characters with some other characters in a string.
• Syntax: str_replace(search, replace, string, count)
• search: Required parameter. Specifies the value to search
• replace : Required parameter. Specifies the value to replace the value in search
• string : Required parameter. Specifies the string to be searched
• count :optional parameter. A variable that counts the number of replacements

• Example 1:
<?php
echo str_replace("world","Rakesh","Hello world!");
?>
Output:
• Hello Rakesh!
String functions
• str_replace():
• Example 2:
<?php
$arr = array("blue","red","green","yellow");
print_r(str_replace("red","pink",$arr,$i));/*Search an array for the value “red", and then replace it
with "pink” */
echo "<br>Replacements: $i";
?>

• Output:
Array ( [0] => blue [1] => pink [2] => green [3] => yellow )
Replacements: 1
String functions
• ucwords() :
• The ucwords() function converts the first character of each word in a string to
uppercase.
• Syntax: ucwords(string, delimiters)
• String: Required parameter. Specifies the string to convert
• Delimiters: Optional. Specifies the word separator character

• Example:
<?php
echo ucwords("hello world!");
?>
Output:
• Hello World!
String functions
• strtoupper() :
• The strtoupper() function converts the string into uppercase

• Syntax: strtoupper(string)
• String: Required parameter. Specifies the string to convert

• Example:
<?php
echo strtoupper("Hello World!");
?>
• Output:
• HELLO WORLD!
String functions
• strtolower() :
• The strtoupper() function converts the string into lowercase

• Syntax: strtolower(string)
• String: Required parameter. Specifies the string to convert

• Example:
<?php
echo strtolower("HELLO WORLD!");
?>
• Output:
• hello world!
String functions
• strcmp() :
• The strcmp() function compares two strings.
• Syntax: strcmp(string1,string2)
• String1: Required parameter. Specifies the first string to compare
• String2: Required parameter. Specifies the second string to compare
• Return Value: This function returns:
• 0 - if the two strings are equal
• > 0 - if string1 is greater than string2
• < 0 - if string1 is less than string2
• Note: The strcmp() function is binary-safe and case-sensitive.

• Example:
<?php
echo strcmp("Hello","Hello")."<br>"; //the two strings are equal
echo strcmp("Hello world!","Hello")."<br>"; //string1 is greater than string2
echo strcmp("Hello","Hello world!"); // string1 is less than string2
?>
Output:
• 0
7
String functions
Sr. No. PHP function Use Example
<?php
The PHP strlen() function returns the length of a
1 strlen() echo strlen("Hello World!");
string.
?>//output: 12
<?php
The PHP str_word_count() function counts the
2 str_word_count() echo str_word_count("Hello world!");
number of words in a string.
?> //output: 2
<?php
3 strrev() The PHP strrev() function reverses a string. echo strrev("Hello World!");
?>//output: !dlroW olleH
The strpos() function finds the position of the first <?php
4 strpos() occurrence of a substring inside another string. echo strpos("I am a PHP programmer", "am");
?> //output: 2
<?php
The PHP str_replace() function replaces some echo str_replace("world","Rakesh","Hello
5 str_replace()
characters with some other characters in a string. world!");
?> //output: Hello Rakesh!
<?php
Convert the first character of each word to
6 ucwords() echo ucwords("hello world!");
uppercase
?> //output: Hello World!
<?php
7 strtoupper() Convert a string a uppercase letters echo strtoupper("Hello World!");
?> //output: HELLO WORLD!
<?php
8 strtolower() Convert a string to lowercase letters echo strtolower("HELLO WORLD!");
?> //output: hello world!
Compare two strings(case-sensitive) and
returns 0 - if the two strings are equal, <?php
returns positive numbrer( >0 ) - if string1 is greater echo strcmp("Hello
9 strcmp()
than string2,returns negative numbrer( <0 ) - if World!","Hello"); ?>
string1 is less than string2 //output: 7
String functions

Example:
Write a PHP program to calculate length of string and count number of words
in string without using string functions
<?php
$str="Hello World!";
for($i=0;isset($str[$i]);$i++){
}
echo "Length of string is:".$i;

$arr=explode(" ",$str);
echo "<br>number of words in a string are:".count($arr);
?>
Output:
Length of string is:12
Number of words in a string are:2
Function
• A function is a named block of code written in a program to perform some
specific tasks.
• PHP function is a piece of code that can be reused many times.
• PHP provides us with two major types of functions:
• Built-in functions
• User Defined Functions
Built-in functions
• PHP provides us thousands of built-in functions that can be called directly.
• These functions are already coded and stored in form of functions.
• To use these functions we just need to call them as per our requirement .
• The functions like var_dump, fopen(), print_r(), gettype() are examples of built-in
functions .
User Defined Functions
• Apart from the built-in functions, PHP allows us to create our own customized
functions called the user-defined functions.
• A function accepts set of parameter as input, performs operations on these
parameters and returns the result.
• A function will be executed by a call to the function.
• You may call a function from anywhere within a script
User Defined Functions
• Create a Function
• A user-defined function declaration starts with the keyword function, followed by
the name of the function
• A function name must start with a letter or an underscore.
• Function names are NOT case-sensitive
• The syntax for defining an user defined function is as follows:
function function_name([parameters if any])
{
Function body / statements to be executed
}
• Call a Function
• To call the function, just write its name followed by parentheses ()
User Defined Functions
• PHP User defined function without parameters:
• Example:
<?php
function sayHello() //declare and define a function
{
echo "Hello,Welcome to PHP function";
}
sayHello(); // calling function
?>

Output: Hello,Welcome to PHP function


User Defined Functions
• PHP User defined function with parameters:
• PHP Parameterized functions are the functions with parameters. You can pass any
number of parameters inside a function. These passed parameters act as variables inside
your function.
• Example:
• Following example of user defined function, that takes two integer parameters and add
them together and then print their sum
<?php
function add($x, $y) //declare and define a function
{ $sum=$x + $y;
echo "addition is: $sum";
}
add(10,20); // calling function
?>
Output: addition is: 30
User Defined Functions
• PHP Function returning value:
• A function can return a value using the return statement in conjunction with a value.
• The return statement stops the execution of function and sends value back to calling
code
• Example:
• Following example of user defined function ,that takes two integer parameters and add
them together and then return their sum to calling program.
• Note that return keyword is used to return a value from a function.
<?php
function add($x, $y) //declare and define a function
{$sum=$x + $y;
return $sum;
}
$result=add(10,20); // calling function
echo "addition is: $result";
?>
• Output: addition is: 30
User Defined Functions
Example: Write PHP program to find largest of two number
<?php
function findLargest($num1, $num2){
if($num1 > $num2) {
return $num1;
}
elseif($num2 > $num1){
return $num2;
}
else{
return "Both numbers are equal";
}
}
$num1 = 10; $num2 = 20;
echo "The largest number between $num1 and $num2 is: ". findLargest($num1, $num2);
?>
Output: The largest number between 10 and 20 is: 20
Variable function
• When variable name has parentheses(with or without parameters) in front of it then PHP calls
variable function and once variable function is called, then PHP parser looks for a function whose
name same as value of variable and execute it, Such a function is called variable function.
• PHP allows us to store function name in a string variable and use variable to call the function.
• This feature is useful in implementing callbacks, function tables, etc.
• Variable functions don’t work with certain language constructs likes echo , print , unset, include,
require ,etc.
• Variable function without parameter
• Example 1:
<?php
function sayHello() //declare and define a variable function
{
echo "Hello, Welcome to PHP variable function";
}
$var="sayHello";
$var();// calling variable function
?>
• Output : Hello,Welcome to PHP variable function
Variable function
• Variable function with parameters:
• Example 2:
<?php
function add($x,$y) //declare and define a variable function
{
$sum=$x+$y;
echo "addition is:".$sum;
}
$var="add";
$var(10,20); // calling variable function
?>
Output: addition is : 30
Variable function
• Variable function returning value:
• Example 3:
<?php
function add($x,$y) //declare and define a variable function
{
$sum=$x+$y;
return $sum;
}
$var="add";
echo "addition is:".$var(10,20); // calling variable function
?>
Output: addition is : 30
Anonymous Function
• Anonymous Function are functions in PHP that do not have a specific name and
can be defined inline wherever they are needed.
• Anonymous Function, also known as closures or Lambda function,
• They are useful for situations where a small, one-time function is required, such as
callbacks for array functions, event handling, or arguments to other functions.
• Anonymous Function can be :
• Stored in a variable,
• Can access global variables using use keyword
• Passed as arguments to other function or
• Returned from other functions
The syntax for defining an anonymous function is as follows:
$var=function ($arg1, $arg2)
{
//block of statements;
};
Anonymous Function
• Anonymous Function without parameters:
• Example:
<?php
// Defining and calling Normal Function
function normal(){
echo "Normal Function" ;
}
normal();
//Defining and calling anonymous function
$var=function(){
echo "<br>Anonymous function";
};
$var();
?>
Output:
Normal Function
Anonymous function
Anonymous Function
• Anonymous Function with parameters:

• Example:
<?php
//define and use anonymous function
$var=function($x, $y){
$sum = $x + $y;
echo "addition is:".$sum;
};

$var(10,20);//calling anonymous function


?>

• Output:
addition is:30
Anonymous Function
• Anonymous function returning value:
• Example:
<?php
//define and use anonymous function
$var=function($x,$y){
$sum=$x+$y;
return $sum;
};
echo "addition is:" .$var(10,20); //calling anonymous function
?>
• Output:
addition is:30
Anonymous Function

• Variable scope in anonymous function:

Example:
<?php
$a=10; //global variable
$b=20; //global variable

$var=function($x,$y) {
$sum=$x+$y;
echo "addition is: $sum";
};
$var($a,$b); //global variable passed as argument to anonymous function
?>
• Output:
addition is:30
Anonymous Function
• Anonymous function as a closure:
• Closure is an anonymous function that can access global variable with the help of use keyword
Example:
<?php
$a=10; //global variable
$b=20; //global variable
//anonymous function access global variable with the help of use keyword
$var=function() use($a,$b){
$sum=$a+$b;
echo "addition is: $sum";
};

$var(); calling anonymous function


?>
Output: addition is: 30
Basic Graphics Concepts:
• Creating Images
• Images with text
• Scaling Images
• Creation of PDF document
• In PHP, "GD functions" refer to a set of built-in functions within the GD (Graphics Draw) library,
which allows us to create images, setting colors, drawing lines, shapes, adding effects , adding text
to images and outputting images in various formats like JPEG, PNG, and GIF.
• Common GD functions:
• imagecreate: Creates a new blank image
• imagecreatetruecolor: Creates a new true-color image
• imagecolorallocate: Allocates a color for an image
• imageline: Draws a line on an image
• imagefill: Fills a region of an image with a color
• imagestring: Writes text on an image
• imagejpeg: Outputs an image as JPEG format
• imagetruecolortopalette: Converts a true-color image to a palette-based image
Creating Image
• Imagecreate() function:
• The imagecreate() function is used to create a new image with given size.

• Syntax: imagecreate( $width, $height )


• Parameters:
• $width: mandatory parameter ,It specifies the image width.
• $height: mandatory parameter , It specifies the image height.
• Return Value: This function returns an image resource identifier on success, FALSE on
errors.

• Example: $image = imagecreate(500,300);


Creating Image
• Imagecreatetruecolor() function
• imagecreatetruecolor() function is used to create a new true-color image with given size.
• In general imagecreatetruecolor() function is used instead of imagecreate() function
because imagecreatetruecolor() function creates high quality images.

• Syntax: imagecreatetruecolor( $width, $height )


• Parameters:
• $width: mandatory parameter, It specifies the image width.
• $height: mandatory parameter, It specifies the image height.
• Return Value: This function returns an image resource identifier on success, FALSE on
errors.
• Example: $image = imagecreatetruecolor(500,300);
Creating Color
• Imagecolorallocate() Function:
• The imagecolorallocate() function used to set the color in an image.
• The imagecolorallocate() function creates each color that is to be used in the image.
• This function returns a color which is given in RGB format.
• Syntax: imagecolorallocate($image, $red, $green, $blue )
• Parameters:
• $image: It is returned by one of the image create functions, such as imagecreate() or
imagecreatetruecolor().
• $red: It specifies the value of red color component.
• $green: It specifies the value of green color component.
• $blue: It specifies the value of blue color component.
• These parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.
• Return Value: This function returns a color identifier on success or FALSE if the color allocation
failed.
• Example: $bg_color = imagecolorallocate($image,0,0,255);
• Note:
• The first call to imagecolorallocate() fills the background color in palette-based images -
images created using imagecreate().
Image with Text
• Imagestring() Function:
• The imagestring() function is used to draw the string horizontally at given coordinates.

• Syntax: imagestring( $image, $font, $x, $y, $string, $color )


• Parameters:
• $image: It is returned by one of the image create functions, such as imagecreate() or
imagecreatetruecolor().
• $font: It specifies the font size. Font size can be 1, 2, 3, 4, 5 for built-in fonts in latin2
encoding.
• $x: It specifies the x-coordinate of the upper left corner.
• $y: It specifies the y-coordinate of the upper left corner.
• $string: It specifies the string to be written on the image.
• $color It specifies the color of text. A color identifier created with imagecolorallocate()
function .
• Return Value: This function returns TRUE on success or FALSE on failure.

• Example: imagestring($image,5, 10,130,"PHP image demo", $txt_color);


Image with Text
• Imagestringup() Function:
• The imagestringup() function is used to draw the string vertically at given coordinates.
• Syntax: imagestringup($image, $font, $x, $y, $string, $color )
• Parameters:
• $image: It is returned by one of the image create functions, such as imagecreate() or
imagecreatetruecolor().
• $font: It specifies the font size. Font size can be 1, 2, 3, 4, 5 for built-in fonts in latin2
encoding.
• $x: It specifies the x-coordinate of the upper left corner.
• $y: It specifies the y-coordinate of the upper left corner.
• $string: It specifies the string to be written on the image.
• $color: It specifies the color for text. A color identifier created with imagecolorallocate()
function .
• Return Value: This function returns TRUE on success or FALSE on failure.

• Example: imagestringup($image,5, 10,130,"PHP image demo", $txt_color);


Creating Images
Example: Write a PHP program to display text on image
<?php
// To define size of an image
$image = imagecreate(500,300);

// To define background color for image


$bg_color = imagecolorallocate($image,0,0,255);

// To define text color of the image


$txt_color = imagecolorallocate($image, 255,0,0);

// Add text on the image


imagestring($image,5, 10,130,"PHP image demo", $txt_color);

//Set the content type header


header("Content-Type:image/png");

// Output png image to browser or to save image in a file


imagepng($image);

//free image resource


imagedestroy($image);
?>
Imagefill() Function
• The imagefill() function used to fill the image with the given color.
• This function performs a flood fill starting at the given coordinate (top left is 0, 0) with the
given color in the image.

• Syntax: imagefill( $image, $x, $y, $color )


• Parameters:
• $image: It is returned by one of the image create functions, such as imagecreate() or
imagecreatetruecolor().
• $x: It specifies the x-coordinate of starting point.
• $y: It specifies the y-coordinate of starting point.
• $color: It sets the color of image. A color identifier created by imagecolorallocate() function.
• Return Value: This function returns True on success or False on failure.
Imagefill() Function
Example: Write a PHP program to fill background color for an image

<?php
$image = imagecreatetruecolor(500,300);

$bg_color = imagecolorallocate($image,0,0,255);

imagefill($image,0,0,$bg_color);

header("Content-Type:image/png");

imagepng($image);

imagedestroy($image);
?>
Imagefilledrectangle() function
• The imagefilledrectangle() function creates a rectangle filled with a given color in the image.
The top left corner of the image is (0, 0).
• Syntax: imagefilledrectangle( $image, $x1, $y1, $x2, $y2, $color )
• Parameters:
• $image: It is returned by one of the image create functions, such as imagecreate() or
imagecreatetruecolor().
• $x1: It specifies the the x-coordinate for point 1.
• $y1: It specifies the y-coordinate for point 1.
• $x2: It specifies the x-coordinate for point 2.
• $y2: It specifies the y-coordinate for point 2.
• $color: This parameter contains the filled color identifier. A color identifier created with
imagecolorallocate() function.
• Return Value: This function returns True on success or False on failure.
Imagefilledrectangle() function
• Example: Write a PHP program to draw a rectangle filled with red color.
<?php
// To define size of an image
$image = imagecreatetruecolor(500, 300);

//To define background color for rectangle


$bg_color = imagecolorallocate($image, 255, 0, 0);

//To fill background color for rectangle


imagefilledrectangle($image, 30, 30, 470, 270, $bg_color);

//Set the content type header


header("Content-type: image/png");

//Output the png image to the browser


imagepng($image);

//free image resource


imagedestroy($image);
?>
Scaling Images
• Imagescale() Function:
• The imagescale() function is used to scale an image using the given new width and height.
• Syntax:
• imagescale( $image, $new_width, $new_height)
• Parameters:
• $image: It is returned by one of the image creation functions, such as imagecreate() or
imagecreatetruecolor().
• $new_width: It specifies the width to scale the image.
• $new_height: It specifies the height to scale the image.
• Return Value: This function return the resource of scaled image on success or False on failure.
Scaling Images
Example:
<?php
// Load image from file
$image = imagecreatefrompng('phplogo.png');

//To scale the image


$img = imagescale($image,500, 300 );

header("Content-type: image/png");
// Output image in the file
imagepng($img,'phplogo1.png');
imagedestroy($img);
?>
Scaling Images
• The imagecopyresized() function: Copy and resize part of an image
• The imagecopyresized() function copies a rectangular portion of one image to another image and
resize it.
• Syntax:
• imagecopyresized(dst_image,src_image, dst_x, dst_y,src_x, src_y, dst_w,dst_h,src_w, src_h)
• Parameters
• 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.
• Return Value: This function returns TRUE on success or FALSE on failure.
• .
Scaling Images
• The imagecopyresampled() function: Copy and resize part of an image with resampling
• The imagecopyresampled() function copies a rectangular portion of one image to another image,
smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a
great deal of clarity.
• imagecopyresampled() function performs additional “resampling”, which results in a better quality
image and to perform resampling it uses interpolation algorithm to calculate new pixel values.
• where as imagecopyresized() function simply stretches or shrinks pixels without any smoothing, which
results in a poor quality image
• Syntax:
• imagecopyresampled(dst_image,src_image, dst_x, dst_y,src_x, src_y, dst_w,dst_h,src_w, src_h)
• Parameters
• 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.
Scaling Images
Example: Resize an image to half of its original size.
<?php
//creates image resource identifier from png file
$image_src = imagecreatefrompng('phplogo.png');

//get width and height of the source image


$width =imagesx($image_src);
$height =imagesy($image_src);

//Reduce width and height to half of its origional


$new_width = $width/2;
$new_height = $height/2;

//creates a new image resource


$image_dest = imagecreatetruecolor($new_width, $new_height);

//Resize the image


imagecopyresized($image_dest, $image_src, 0,0, 0, 0, $new_width, $new_height, $width, $height);

header('Content-Type: image/png');
imagepng($image_dest);
imagedestroy($image_dest);
?>
Scaling Images
Example: Resample an image to half of its original size.
<?php
//creates image resource identifier from png file
$image_src = imagecreatefrompng('phplogo.png');

//get width and height of the source image


$width =imagesx($image_src);
$height =imagesy($image_src);

//Reduce width and height to half of its origional


$new_width = $width/2;
$new_height = $height/2;

//creates a new image resource


$image_dest = imagecreatetruecolor($new_width, $new_height);

//Resample the image


imagecopyresampled($image_dest, $image_src, 0,0, 0, 0, $new_width, $new_height, $width, $height);

header('Content-Type: image/png');
imagepng($image_dest);
imagedestroy($image_dest);
Require() and Include() Functions in PHP:
• The both require() and include() Functions are used to include(or insert) the contents/code/data
of one PHP file to another PHP file(before the server executes it).
• If insert file is missing or there are any kind of errors then require will produce a fatal error
(E_COMPILE_ERROR) and stop the execution of the script.
• If insert file is missing or there are any kind of errors then include will only produce a warning
(E_WARNING) and the continue the execution of the script.
• Syntax:
• include 'filename';
or
require 'filename';
Require() and Include() Functions in PHP:
• Example:
• Assume we have a standard footer file called "footer.php", that looks like this:
<?php
echo "Copyright&copy; 1983-".date("Y"). " https://iotmumbai.bharatividyapeeth.edu";
?>
• To include the footer.php file in a includedemo.php file, use the include statement:
<html>
<body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<?php
echo "<h1>Include demo</h1><br>";
include 'footer1.php';
?>
Output:
</body>
Welcome to my home page!
</html> Some text.
Include demo

Copyright© 1983-2025 https://iotmumbai.bharatividyapeeth.edu


Creation of PDF Document
• For generating a pdf document in PHP, we need some library files.
• FPDF(Free Portable Document Format) is a PHP class that includes different functions for creating
and editing PDF files in PHP.

• The FPDF class supports a variety of features like:


• It provides the choice of measure unit, page format and margins for pdf page
• It provides page header and footer management
• It provides automatic page breaks to the pdf document
• It provides Automatic line break and text justification
• It provides support for various fonts ,colors, encoding and image formats(such as JPEG, PNG and
GIF)

However, because it is a third-party library, it requires some processes before you can use it.
You will need to:
Download the FPDF class for free from the website : https://www.fpdf.org.
Create a folder and extract the FPDF package into it. Let’s say that you have downloaded and
extracted the FPDF package inside a folder called fpdf (or any name you like).
Create a new PHP file called pdfdemo.php inside the same folder and insert the code snippet below.
Save the file and try to access it through your localhost : http://localhost/fpdf/pdfdemo.php
Creation of PDF Document
Example 1 : PHP program that creates a PDF document with some text written on it
<?php
include('fpdf.php'); //include fpdf library
$pdf = new FPDF();// create pdf object of the FPDF class
$pdf->AddPage();//Add a new blank page
$pdf->SetFont('Arial', 'B', 20);// Set the font for the text
$pdf->Cell(80,10,'Hello world!');// Prints a cell with given text
$pdf->Output( );// send PDF to browser
?>
Creation of PDF Document
Program Explanation:
In above program,
1. We need to include the fpdf library file using include() function. The include() function is used
to put data of one PHP file to another PHP file.
2. After including the library file, we create an FPDF object. The object is created in variable $pdf
3. There is no page at the moment, so we have to add one with AddPage() function.
4. Before writing any text on the PDF page, we need to set the font. Using setFont() function the
font is set. The syntax for this function is:
SetFont(string family, string style, float size)
Where
• Family: It indicates the font family. Possible values are 'Arial', 'courier', 'Times', and so on.
• Style: It indicates the font style. Possible values are :
(i) empty string: regular
• (ii) B: bold
• (iii) I: italic
• (iv) U: underline
• Size: Font size in points. default font size is 12
• In above program we are setting 'Arial', bold font with size 20.
Creation of PDF Document
5. A cell is a rectangular area, possibly framed, which contains a line of text.
It is output at the current position. We specify its dimensions, its text , with optional borders,
background color ,The text can be aligned or centered.
$pdf->Cell(80, 10, ‘Hello World!');
Using above statement we are writing the text message ‘Hello World!' at position (x,y)=(80,10).
6. Finally, the document is closed and sent to the browser with Output().
Creation of PDF Document

Output:

If once PDF file is created , download it and save as “my_file.pdf”


Creation of PDF Document
Example 2:
<?php
include('fpdf.php');
$pdf = new FPDF();// create pdf object of FPDF class
$pdf->AddPage();//Add new blank page to PDF
$pdf->SetFont('Courier', 'BIU', 20);// Set the font for text
$pdf->SetTextColor(255,0,0); // Set the color for text
$pdf->Cell(50,50,'PDF Demo');// Prints a cell with given text
$pdf->SetTextColor(100,200,200);
$pdf->Cell(100,150,'another PDF Demo');
$pdf->Output('my_file.pdf','D');// send PDF to browser(I for inline display),(D for download
PDF),(F for saving PDF to a local folder)
?>
Creation of PDF Document
Example 3:
<?php
require('fpdf.php');

$pdf = new FPDF();


$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(0,10,'Welcome to php programming',1,1,'C');
$pdf->Cell(0,10,'Java Programming',1,1,'C');
$pdf->Cell(0,10,'python Programming',1,1,'C');
$pdf->Cell(0,10,'Click here..',1,1,'C',0,'https://iotmumbai.bharatividyapeeth.edu');

$pdf->Output();

?>
Creation of PDF Document
Example 4:
<?php
require('fpdf.php');
$sroll = 101;
$sname = 'Amit';
$smark1 = 60;
$smark2 = 70;

$pdf = new FPDF();


$pdf->AddPage();
$pdf->SetFont('Arial','B',10);
$pdf->Cell(0,10,'Student Information ',1,1,'C');
$pdf->Cell(30,10,'RollNo ',1,0,"C");
$pdf->Cell(80,10,'Name of Student',1,0,'C');
$pdf->Cell(40,10,'Subject1 ',1,0,'C');
$pdf->Cell(40,10,'Subject2 ',1,1,'C');
$pdf->Cell(30,10,$sroll,1,0,'C');
$pdf->Cell(80,10,$sname,1,0,'C');
$pdf->Cell(40,10,$smark1,1,0,'C');
$pdf->Cell(40,10,$smark2,1,1,'C');
$pdf->Cell(30,10,'102',1,0,'C');
$pdf->Cell(80,10,'Shruti',1,0,'C');
$pdf->Cell(40,10,'80',1,0,'C');
$pdf->Cell(40,10,'90',1,1,'C');
$pdf->Output();
//$pdf->Output('student_info.pdf','D');
?>

You might also like