WBP Unit 2
WBP Unit 2
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>";
<?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]";
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));
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)
• 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.
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
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");
• 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
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.
• 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
?>
• Example:
<?php
//define and use anonymous function
$var=function($x, $y){
$sum = $x + $y;
echo "addition is:".$sum;
};
• 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
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";
};
<?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);
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');
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');
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© 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
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:
$pdf->Output();
?>
Creation of PDF Document
Example 4:
<?php
require('fpdf.php');
$sroll = 101;
$sname = 'Amit';
$smark1 = 60;
$smark2 = 70;