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

PHP Web Development Notes 1 3 Unit

The document provides an overview of PHP, a server-side scripting language used for web application development. It covers PHP syntax, advantages, variable scope, data types, operators, and control statements, along with examples for each concept. The document serves as an introductory guide for understanding PHP programming and its functionalities.

Uploaded by

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

PHP Web Development Notes 1 3 Unit

The document provides an overview of PHP, a server-side scripting language used for web application development. It covers PHP syntax, advantages, variable scope, data types, operators, and control statements, along with examples for each concept. The document serves as an introductory guide for understanding PHP programming and its functionalities.

Uploaded by

NTR Thor OP
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 213

WEB BASED

APPLICATION
DEVELOPMENT
WITH
1
PHP
Unit – 01
Expression
andControl
Statements in
PHP

2
PHP Definition:-
• The PHP Hypertext Preprocessor (PHP) is a programming language that allows
web developers to create dynamic content that interacts with databases. PHP is
basically used for developing web based software applications
• It is integrated with a number of popular databases, including MySQL,
PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server.
• PHP supports a large number of major protocols such as POP3, IMAP, and LDAP.
PHP4 added support for Java and distributed object architectures.
• PHP Syntax is C-Like. Server side interpreted, non-compiled and scripting
language
• Written with HTML as code is executed by the server, but the result is displayed
to the user as plain HTML
• It is used to manage dynamic content, databases, session tracking, even build
entire e-commerce sites.

3
Science
Calculations

System

Syste
m

C uses curly
braces { }
for code
blocks. Scripting/
Interprete
d
PHPAdvantages:-
• Simplicity
• Efficiency
• Security
• Flexibility
• Familiarity
• Open Source
• Database
• Support
• Maintenance
• Scripting Langauge
5
Syntax of PHP :-
• Example
• Syntax <html>
A PHP script starts with <body>
<?php and ends with ?> <h1>My first PHP page</h1>
<?php
<?php
echo “Welcome to Online class”; echo “Welcome to Online class”;
?> ?>

</body>
The default file extension for PHP </html>
files is ".php"
6
Embedding PHP within HTML :-
• Inside a PHP file you can write • Example
HTML like you do in regular HTML <!DOCTYPE html>
pages as well as embed PHP code <html lang=“en”>
for server side execution. <head>
• When it comes to integrating PHP <meta charset=“UTF-8”>
code with HTML content, you need to <title>How to put PHP in HTML - Simple
enclose the PHP code with the PHP Example</title>
start tag <?php and the PHP end tag </head>
?>. <body>
• The important thing in the above <h1><?php echo " Welcome to Online
class.“; ?></h1>
example is that the PHP code is
wrapped by the PHP tags. </body>
</html>

7
PHP Comments:- • Example
• A comment in PHP code is a line that is <!DOCTYPE html>
<html>
not executed as a part of the program. <body>
Its only purpose is to be read by
someone who is looking at the code. <?php
// This is a single-line comment
• Purpose of comment is to make code
# This is also a single-line comment
more readable. It may help other
developer to understand the code.
/* This is multiline comment block that
• PHP support single line as well as
span across more than.
multiline comments.
*/
• To start a single line comment either ?>
start with two slash (//) or hash (#). </body>
• Multiline comments start with /* and </html>
end with */
8
PHP echo and Print:-
• Example
• In PHP, there are 2 way to get output or <?php
print output: echo and print. echo "Hello world!<br/>"; // display string
• The echo statement is used with or echo "This ", "string ", "was ", "made ", "with
without parentheses: echo or echo().
multiple parameters.<br/>"; // strings as multiple
• The echo statement can display $a= “Hello, PHP”;
anything that can be displayed to the
browser: string, number, variable value $b= 5; $c=10;
and result of expression . echo “$a<br/>”;
• The PHP print statement is similar to the echo $b.”+”.$c.”=“; //Display variable
echo statement and use as a alternative. echo $b+$c;
• echo has no return value while print has a ?>
return value of 1 so it can be used in </body> </html>
expressions
9
PHP Print:-
• Example
• In PHP, echo can take multiple <?php
parameters (although such usage is print "Hello world!<br/>";
rare) while print can take one
argument. $a= “Hello, PHP”;
• echo is marginally faster than print. $b= 5;
Output :- $c=10;
print “$a<br/>”;
Hello world!
print $b.”+”.$c.”=“; //Display variable
Hello, PHP
print $b+$c;
5+10=15
?>

10
PHP Variable Scope:-
• Example
•Local Variable:- <?php
• The variable declared within a $num=10;
function called Local variable. function local_var()
• So Local Variable scope is within {
function only. $num=50;
• Local Variable can not accessed echo “local num=$num<br/>”;
outside that function.
} local_var();
• And outside function such a
variable treat as different variable. echo “Variable num outside
local_var()=$num<br/>”;
?>
11
PHP Variable Scope:
-
•Global Variable:- • Example

• The variable declared outside a <?php


function called Local variable. $num=10;
• So Global Variable scope is all function local_var()
function. {
• Global Variable can accessed global $num;
outside that function. echo “Access global variable within
• To get access within a function we function=$num<br/>”;
need to use “global” keyword } local_var();
before the variable . echo “Global Variable num outside of
local_var()=$num<br/>”;
?>
12
PHP $ and $$ Variable:-
• Example
• The $var is normal variable that <?php
store any value.
$a=“Hi”;
• The $$var is reference variable that
store the value of $variable inside it. $$a=“GPG”;
• $a represent variable but $$a echo $a.“<br/>”;
represent a variable with the echo $$a.“<br/>”; // echo “$$a<br/>;”
content of $a.
$$a=$($a) echo $Hi;
Output:- ?>
Hi
GPG
GPG
13
PHP Operators:-
 Operators are used to perform operations on variables and values.

 PHP divides the operators in the following groups:

• Arithmetic operators
• Assignment operators
• Comparison operators
• Increment/Decrement operators
• Logical operators
• String operators
• Array operators
• Conditional assignment operators

14
PHP Arithmetic Operators:
-

15
PHP Assignment Operators:
-

16
PHP Comparison Operators:
-

17
PHP Increment / Decrement Operators:
-

18
PHP Logical Operators:
-

19
PHP String Operators:
-

20
PHP Array Operators:
-

21
PHP Conditional Assignment Operators:
-

22
PHP Data Types:-
• PHP String
• Variables can store data of different • A string is a sequence of characters, like
types, and different data types can do
different things. "Hello world!".
• PHP supports the following data types: • A string can be any text inside quotes. You
1) String can use single or double quotes:
2) Integer <?php
3) Float (floating point numbers - also $x = "Hello world!";
called double) $y = 'Hello GPG!';
4) Boolean
5) Array echo $x;
6) Object echo "<br>";
7) NULL echo $y;
8) Resource ?>
23
PHP Integer:-
• In the following example $x is an integer. The
• An integer data type is a non-decimal PHP var_dump() function returns the data
number between -2,147,483,648 and type and value:
2,147,483,647 <html>
• Rules for integers: <body>
1) An integer must have at least one <?php
digit
$x = 5985;
2) An integer must not have a decimal
point var_dump($x);
3) An integer can be either positive or ?>
negative </body>
4) Integers can be specified in: decimal </html>
(base 10), hexadecimal (base 16),
octal (base 8), or binary (base 2)
notation
24
PHP Float:
- • A float (floating point number) is a • In the following example $x is an integer. The
number with a decimal point or a PHP var_dump() function returns the data
number in exponential form. type and value:
<html>
<body>
• Output:-
<?php
float(10.68) $x = 10.68;
var_dump($x);
?>
</body>
</html>

25
PHP Boolean:-
• Example:-
• A Boolean represents two possible <?php
states: TRUE or FALSE. $a = 11;
• Booleans are often used in $b = 11.22;
conditional testing. You will learn $c=“Hello”;
more about conditional testing in a $d= True;
later chapter of this tutorial. var_dump($a);
• Output:- var_dump($b);
int(11) var_dump($c);
float(11.22) var_dump($d);
string(5) “Hello” ?>
bool(true)

26
PHP Array:-
• Example:-
• An array stores multiple values in • In the following example $cars is an array.
one single variable. The PHP var_dump() function returns the
data type and value:
<html>
• Output:- <body>
array(3) { [0]=> string(5) "Volvo" <?php
[1]=> string(3) "BMW" [2]=> string(6)
$cars = array("Volvo","BMW","Toyota");
"Toyota" }
var_dump($cars);
?>
</body>
</html>
27
PHP Object:
- • Classes and objects are the two • Example:-
main aspects of object-oriented • <?php
class Car {
programming. public $color;
public $model;
• A class is a template for objects, public function construct($color, $model) {
and an object is an instance of a $this->color = $color;
$this->model = $model;
class. }
public function message() {
• When the individual objects are return "My car is a " . $this->color . " " . $this->model . "!";
}
created, they inherit all the }
properties and behaviors from the
class, but each object will have $myCar = new Car("black", "Volvo");
echo $myCar -> message();
different values for the properties. echo "<br>";
$myCar = new Car("red", "Toyota");
echo $myCar -> message();
?>

28
PHP NULL Value:
- • Null is a special data type which can • Example:-
have only one value: NULL.
• A variable of data type NULL is a <html>
variable that has no value assigned <body>
to it. <?php
• If a variable is created without a $x = "Hello world!";
value, it is automatically assigned a $x = null;
value of NULL.
var_dump($x);
• If a variable is created without a ?>
value, it is automatically assigned a
</body>
value of NULL.
</html>

29
PHP Resource:-
• Example:-
• The special resource type is not an <html>
actual data type. It is the storing of <body>
a reference to functions and <?php
resources external to PHP.
$f1 = fopen(“note.txt“,”r”);
• A common example of using the var_dump($f1);
resource data type is a database
call. echo”<br>”;
$link=mysql_connect(“localhost”,”root”,””);
var_dump($link);
?>
</body>
</html>
30
PHP Type Juggling:-
• Example:-
• Means dealing with variable type. <html>
• In PHP a variable type is determined <body>
by the context in which it is used. <?php

• If an Integer value is assign to a $var1= 1;


variable, it become a integer. $var2=“20”;
$var3=$var1+$var2;
• If an String value is assign to a
variable, it become a String. $var1=$var1+1.3
$var1=5*”10 small birds”;
• PHP does not required explicit type
?>
definition in a variable declaration.
</body>
• The conversion process whether
</html>
explicit or implicit known as…….. 31
PHP Type Casting:-
• Typecasting is a way to convert one • Example:
- <html>
data type.
type variable into different <body>
• A type can be cast by inserting one <?php
of the cast in front of variable. $count=“5”;
• Output:- echo gettype($count);
string $count is a string
settype($count,’int’);
integer
echo gettype($count);
$count is a integer
?>
</body> </html>
32
PHP Decision Making Control Statements:
-
•If Statement:- • Example:-

• The if statement is used to execute <html>


block of code only if the specified <body>
condition is true. <?php
• Syntax:- $a=10;
if(condition) if($a>0)
{
{
echo “The number $a is Positive”;
// code to be execute
}
} ?>
</body> </html>

33
PHP Decision Making Control Statements:-
•If-else Statement:- • Example:-
• The if...else statement executes some <?php
code if a condition is true and another $t = date("H");
code if that condition is false.
• Syntax:- if ($t < "10") {
echo "Have a good morning!";
if (condition) }
{
else
// code to be executed if condition is true;
{
} else echo "Have a good day!";
{ }
// code to be executed if condition is false; ?>
}

34
PHP Decision Making Control Statements:-
•Nested-If Statement:- • Example:-
• Means an if block inside another if block. <?php
We use it when we have more than 2 $t = date("H");
condition and also called as if-else-if
statement if ($t < "10") {
• Syntax:- echo "Have a good morning!";
if (condition) }
{ // code to be executed1 if condition is true; elseif ($t < "20") {
} elseif (condition) echo "Have a good day!";
{ // code to be executed2 if condition is true; }
} else else {
{ // code to be executed1 if both condition1 and echo "Have a good night!";
condition2 are false }
} ?>

35
PHP Decision Making Control Statements:-
• Switch Statement:- • Example:-
• The switch statement is used to perform different actions
based on different conditions. <?php
• Use the switch statement to select one of many blocks of code to be $favcolor = "red";
executed.
switch ($favcolor) {
• Syntax:-
case "red":
switch (n) {
case label1:
echo "Your favorite color is red!";
code to be executed if n=label1;
break;
break;
case "blue":
case label2:
echo "Your favorite color is blue!";
code to be executed if n=label2;
break;
break; case "green":
case label3: echo "Your favorite color is green!";
code to be executed if n=label3; break;
break; default:
... echo "Your favorite color is neither red, blue, nor
default: green!";
code to be executed if n is different from all labels; }
} ?>

36
PHP Break and Continue Statements:-
•Break Statement:- • Example:-
•The keyword break ends execution <?php
of the current for, for each, while, for($i=1; $i<=5; $i++)
do while or switch structure. {
• When break executed inside loop echo”$i<br/>”;
the control automatically passes to if($i==3)
the first statement outside loop.
{
•Output:- break;
1 }
2 }
3 ?>

37
PHP Break and Continue Statements:-
•Continue Statement:- • Example:-
•It is used to stop processing the <?php
current block of code in the loop for($i=1; $i<=5; $i++)
and goes to the next iteration. {
• It is used to skip a part of the body if($i==3)
of loop under certain condition. {
•Output:- continue;
1 }
2 echo”$i<br/>”;

4 }
?>
5
38
PHP Loop Control Statements:-
•while Statement:- • Example:-

•It is execute block of code if and as <?php


long as a test condition is true. $i=0;
• While is an entry controlled loop while($i<=10)
statement.
{
•Syntax:- echo”$i<br/>”;
while(if the condition is true) $i+=2;
{ }
// code is executed ?>
}
39
PHP Loop Control Statements:-
•Do- while Statement:- • Example:-
• It is exit control loop which means <?php
that it first enter the loop, execute
the statements and then check $i=1;
condition. do
• Statements is executed at least once .
{
•Syntax:-
echo”$i<br/>”;
do
{ $i+=2;
// code is executed } while($i<10);
} while(if the condition is true); ?>

40
PHP Loop Control Statements:-
•For Statement:- • Example:-
• It is used when you know how many <?php
time you want to execute a
statement or a block of statement. $sum=0;
for($i=0;$i<=10;$i+=2)
• Also known as entry controlled loops.
•Syntax:- {
for(initialization expression; echo”$i<br/>”;
test condition; update exp.)
{
$sum+=$i;
// code is executed }
} echo “Sum=$sum”;
?>
41
PHP Loop Control Statements:-
•foreach Statement:- • Example:-
•It is used for array and object. <?php
• For every counter of loop, an array $arr= array (10,20,30,40,50);
element and the next counter is
shifted to next element. foreach($arr as $i)
•Syntax:- {
foreach (array_element as echo”$i<br/>”;
value) }
{ ?>
// code is executed
}
42
Unit – 02
Arrays,
Functions
andGraphics

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

48
Indexed or Numeric Array:-
• Output:-
• Syntax 1 Example:- Computer Engg.
<?php Information Tech.
$course[0] = “Computer Engg.”; Civil
$course[1] = “Information Tech.”;
$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:- •Syntax:-
•This type of array is similar to
indexed array but instead of <?php
linear storage, every value can
be assigned with user define $variable_name*‘key_name’+=value;
key of string type.
•Associative arrays are arrays $variable_name=array(‘key_name’
that use named keys that you => value,….......);
assign to them. ?>
•An array with a string index
where instead of linear storage,
each value assigned a specific
key. 52
Associative Arrays:- •Example 1:-
•There are two ways to create <?php
an associative array: $age = array("Peter"=>"35",
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
"Ben"=>"37", "Joe"=>"43"); echo “Ben age is=”, $age*“Ben”+;
Or:- ?>
$age['Peter'] = "35"; Output:-
$age['Ben'] = "37"; Ben age is= 37
$age['Joe'] = "43";

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:- •Syntax:-
•These are array that contain array (
other nested array. array (elements….),
•An array which contain single
or multiple arrays within it an array (elements….),
can be accessed via multiple ………
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:-
// accessing elements
•Example 1:- echo “Ram Email id is:”
<?php .$person*0+*“email’”+
// Define multidimension array echo “Laxman Age is:”
$person = array( .$person*1+*“age’”+
array(“name => “Ram”, “age” =>
“20”, “email” => [email protected]”),
?>
array(“name => “Laxman”, “age” => Output:-
“18”, “email” => [email protected]”), Ram Email id is: [email protected]
array(“name => “Sita”, “age” => “19”, Laxman Age is: 18
“email” => [email protected]”)
);
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:
<?php ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
$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:
-
• Outpu
t:-
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 :
extract($course); echo
- “CO=$CO<br>”;echo
“IT=$IT<br>”; echo
•You can use extract() function “CE=$CE<br>”;
?>
to extract data from array and </body> </html>
store it in variables.
<html>
<title> Array </title> Output:
<body> CO=Computer Engg.
<?php IT=Information Tech.
$course*“CO”+ = “Computer Engg.”; CE=Civil
$course*“IT”+ = “Information Tech.”;
$course*“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:-
Syntax:-
•Imploding and Exploding are string implode(separator, array);
couple of important functions
of PHP that can be applied on • The implode() function accept
strings or arrays. two parameter out of which one
•The implode() is a built-in is optional and one is
function in PHP and is used to mandatory.
join the element of an array.
• Separator:-
•The implode function return a
string from the element of an • Array:-
array.
64
Implode :-
echo $text;
•Example:- ?>
<html> </body>
</html>
<head>
<title> array </title> Output:-
<body>
<?php Computer Engg., Information Tech.,
$course[0] = “Computer Engg.”; Civil
$course[1] = “Information Tech.”;
$course[2] = “Civil”;
$text=implode(“,”,$course); 65
Implode :-
// join without separator
•Example without separator:- print_r(implode(“-”,$inputArray));
<html> ?>
</body>
<head>
</html>
<title> array </title>
<body> Output:-
<?php
$inputArray= array(‘CO’, ‘IF’, ‘CE’); COIFCE
CO-IF-CE
// join without separator
print_r(implode($inputArray));
print_r(“<BR>”); 66
Explode:-
•The explode() function break a • The implode() function accept
string into an array. three parameter out of which
•The explode() is a built-in one is optional and two is
function in PHP is used to split mandatory.
a string in different string. • Separator:-
•The explode() function split a
string based on the string
delimeter. • OrignalString:-
•Syntax:-
• NoOfElements
array explode(separator,
OrignalString, NoOfElements);
67
Explode :-
?>
•Example:- </body>
<html> </html>

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

Electrical Engg
Deleting Array Element:-
unset($course[1]);
•Example 1:- echo “Before Deletion: <br>”;
<?php print_r($course);
$course = array(“CO”, “IT”, echo “Delete entire array
“ME”, “CE”); elements: <br>”;
echo “Before Deletion: <br>”; unset($course[1]);
?>
echo $course*0+, “<br>”;
• Output:-
echo $course*1+, “<br>”; Array ([0]=> CO [2]=> ME [3]=> CE)
echo $course*2+, “<br>”; Delete entire array elements:
echo $course[3], “<br>”;
74
Deleting Array Element:-
•Example 2:- echo “After Deletion: <br>”;
<?php $course*1+ = “ ”;
$course*0+ = “Computer Engg.”;
for($i=0; $i<count($course);$i++)
$course*1+ = “Information Tech.”;
$course*2+ = “Civil”; {
$course[3] = “Electrical Engg.”; echo $course*$i+, “<br>”;
echo “Before Deletion: <br>”; }
echo $course*0+, “<br>”; ?>
echo $course*1+, “<br>”;
echo $course*2+, “<br>”;
echo $course[3], “<br>”;
75
Deleting Array Element :
 Reducing an array:-
- • The array_reduce() function
•Output:- apply a user define function to
Before Deletion: each element of an array, so as
Computer Engg. to reduce the array to a single
Information Tech. value.
Civil • Syntax:-
Electrical Engg. • Mixed array_reduce(array
After Deletion: $array, callable $callback
Computer Engg. [, mixed $initial = null])
Civil
76

Electrical Engg
Reducing Array Element :-
 Array_search:-
•Example:- • The array_search() function an
<?php array for a value and return the
$n = array(1, 3, 5, 7); key
• Syntax:-
$total = array_reduce($n,
‘add’); • Mixed array_reduce (mixed
$to_find, array $input [, bool
echo $total;
$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 :-
• ksort() - sort associative arrays in
• Sorting refer to ordering data in ascending order, according to
an alphanumerical, numerical
order and increasing or the key
decreasing fashion. • arsort() - sort associative arrays
• Sorting function for array in PHP in descending order, according
•sort() - sort arrays in ascending to the value
order • krsort() - sort associative arrays
•rsort() - sort arrays in descending in descending order, according
order
to the key
•asort() - sort associative arrays in
ascending order, according to the
value
79
sort() and rsort() in Array :-
echo “After sorting in Ascending
• Example:- order:<br>”;
<?php sort($num);
$num = array(40, 61, 2, 22, 13); $arrlen=count($num);
echo “Before sorting:<br>”; for($x=0; $x<$arrlen; $x++)
{
$arrlen=count($num);
echo $num*$x+, “<br>”;
for($x=0; $x<$arrlen; $x++) }
{ echo “After sorting in Descending
echo $num[$x], “<br>”; 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 :-
echo "<br>";
• Example:- }
<?php echo “Sorting according to Key:<br>”;
$age = array("Peter"=>"35", ksort($age);
"Ben"=>"37", "Joe"=>"43"); foreach($age as $x => $x_value)
echo “Sorting according to {
Value:<br>”; echo "Key=" . $x . ", Value=" .
asort($age); $x_value;
foreach($age as $x => $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 merge two or more
- array with array_mearge()
• You can also cut up and
merge array when needed. • Syntax:-
• Suppose you have 4 course in
array of course and you want array_merge(array1, array2,…..);
to get a subarray consisting of
last 2 items.
•You can do this with
array_slice() function
•Syntax:-
array_slice(array, start, length, 85
preserve);
Splitting Array :-
echo “After Spliting array: <br>”;
• Example:- subarray = array_slice($course, 1,
<?php 2);
$course*0+ = “Computer Engg.”; foreach($subarray as $value)
$course*1+ = “Information Tech.”; {
$course*2+ = “Civil”; echo “Course: $value<br>”;
echo “Before Spliting array: <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 :-
echo “Subject: $value<br>”;
• Example:- }
<?php ?>
$sem5 = array(“ACN”, “OSY”, Output:-
“SEN”); Subject: ACN
$sem6 = array(“WPD”, “JAVA”, Subject: OSY
“Python”); Subject: SEN
$subject = array_merge($sem5, Subject: WPD
$sem6); Subject: JAVA
foreach($subject as $value) { 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 built start with word function:
-in functions, and in addition
you can create your own
custom functions.
90
PHP Functions and its Types:
<body>
- <?php>
• Syntax:- function writeMessage()
function functionName()
{
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:-
echo “In simple()<br/>”;
• PHP support the concept }
variable function. function data($arg =“”) ,
• Means that if variable name is echo “In data(); argument was
parentheses appended to it, ‘$arg’.</br>”;
PHP will look for a function }
with same name. $func = ‘simple’;
$func();
• Example:- $func = ‘data’;
<?php> $func(‘test’) ?>
function simple() 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:-
• But the assignment must surround
• PHP string is a sequence of the string with quote mark (“…” or
characters i.e. used to store ‘…’)
and manipulate text .  Single quoted string:-
• String is one of the data type <?php
supported by PHP. $name = ‘Ram’;
• The string variable can $str = ‘Hello $name’;
contain alphanumerical echo $str “br>”;
characters. var_dump(‘Hello Ram’);
• A “string” of text can be ?>
stored in a variable in much Output: Hello $name
the same way as a numerical string(9) Hello Ram
value. 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 :-
• u: display as an unsigned
•%: To display %. decimal number.
• b: display in Binary number. • x: display as a hexadecimal
•c: display as the corresponding number.
ASCII character.
•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:-
Example:-
•PHP Date function is an In-built <?php
function that works date data echo “Today’s Date is:”;
type. $today = date(“d/m/Y”);
•The PHP date function is used echo $today;
?>
to format a date or time into a
human readable format.
• Output:-
•Syntax:- Today’s Date is: 01/04/2021
date(format, timestamp);

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

120
Basic Graphics Concept:-
• Creating an Image:-
•PHP support basic computer • The imagecreate() function is used to
graphics. An image is a create a new image.
rectangle of pixels of various • Syntax:-
colors. imagecreate(x_size, y_size);
• x_size and y_size parameter are in
•Computer usually create color
pixel.
using a color theory model
called RGB model. • Example:-
$img_height= 200;
•The three basic color that are $img_width= 400;
combine to create the colors $img= imagecreate($img_height,
that we see on the computer $img_width);
display.
121
Basic Graphics Concept:-
• You can pass RGB value on
•It is preferred to use imagecolorallocate() to set color.
imagecreatetruecolor() to • If you want solid red the you had
create a image instead of pass red value 0-255 and blue
imagecreate(). and green value 0.
•Because the image processing
occurs on the highest quality $bg_color= imagecolorallocate($img,
image possible which can be 200, 0, 0);
create using
imagecreatetruecolor() .
•To set a colors to be used in
image use imagecolorallocate() 122
Basic Graphics Concept:-
• Example1:-
•To send JPEG image back to <?php
browser, you have to tell the $img_height= 200;
Brower you are doing so with $img_width= 400;
the header function to set the
$img= imagecreate($img_height,
image type.
$img_width);
•You sent the image with the $bg_color= imagecolorallocate($img,
imagejpeg() function. 200, 0, 0);
•Imagegif():- header(‘Content-Type:image/jpeg);
•imagejpeg() imagejpeg($img);
•Imagewbmp():- ?>
•Imagepng():- 123
Create Image:-
imagedestroy($im);
•Example1:- print "<img
<?php src=image.png?".date("U").">";
$img_height= 200; ?>
$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 :-
• <?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:-
• Example:- png.php file name
•The imagestring() function is an <?php
inbuilt function in PHP which is header(‘Content-Type:image/jpeg);
used to draw the string $img= imagecreate(150, 50);
horizontally. $bg_color= imagecolorallocate($img,
220, 230, 140);
•This function draw the string at $txt_color= imagecolorallocate($img,
given position. 0, 0, 0);
•Syntax:- Imagestring( $img, 5, 6, 17, “Welcome
Imagestring( $image, $font, $x, to GPG”, $txt_color);
$y, $string, $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 PDFDocument:-
 Choice of measure unit, page
•FPDF is a PHP class which format and margins.
allows generating PDF file with  Page header and footer format.
pure PHP that is to say without  Automatic line break and text
using a PDFlib library. justification.
•F from FPDF stand for free.  Image format (JPEG, GIF, and
•We may use it for any kind of PNG)
usage and modify it to suite we  Color and line.
need.  Page compression.
•Features of FPDF:-
 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


astring.
144
Happy
Learning
Thank You
!

145
Unit- 03
Object
Oriented
Concept in PHP

146
Advantage of OOP:-
• OOP is an approach to software development that makes it easy to map
business requirement to code modules.
• PHP is OOP language, is a type of PL principle added to PHP, that helps in
building complex, reusable web application.
• OOP invoke the use of classes to organize the data and structure of application.
• We model our problems and process using object. So object oriented
application consist object that collaborate with each other to solve the problem
• By using OOP in PHP we can create modular web application and perform any
activity in the object model structure.
• By using OOP there is opportunity for code reuses within given application as
well as across different project.

147
Basic OOP Concepts:-
• Classes:- This is a programmer-defined data type, which includes local
functions as well as local data.
• Objects:- An individual instance of the data structure defined by a class.
• Properties:- Characteristics of a class or object are known as properties.
• Methods:- The behavior of a class that is, action associated with class.
• Member Variable:- An individual instance of the data structure defined by a
class.
• Member function:- These are the function defined inside a class and are
used to access object data.
• Inheritance:- When a class is defined by inheriting the existing function of a
parent class then it is called inheritance.
• Parent Class:- A class that is inherited from another class.
148
Basic OOP Concepts:-
• Child Class:- A class that inherits from another class. This is also called a
subclass or derived class.
• Polymorphism:- This is an object-oriented concept where the same function
can be used for different purposes
• Overloading − A type of polymorphism in which some or all operators have
different implementations depending on the types of their arguments.
• Data Abstraction − Any representation of data in which the implementation
details are hidden.
• Encapsulation − refers to a concept where we encapsulate all the data and
member functions together to form an object.
• Constructor & Destructor:- Object Formation and Object Deletion.

149
Creating Classes and Object in PHP:-
• A class is template for object, and • Create Object:-
object is an instance of class. • Example:-
<?php
• Syntax:- class Car
<?php {
class classname_of_class }
{ $Maruti = new Car();
$Honda = new Car();
// code is here
print_r($Maruti );
}
print_r($Honda );
?>
?>
150
Creating and Using Property:
- • Class Prosperity are very similar to  Declaring Properties:-
variables.
 Understanding Property Visibility:- class MyClass
•Public:- Access by any code, {
whether that code is inside or
outside the class. pubic $property1;
•Private:- Access only by the code private $property2;
inside the class. protected $property3;
•Protected:- Like private property }
but difference is any class that
inherits from the class can access.

151
Creating and Using Property:
- • Example:- // Methods
function set_name($name)
{
<?php
$this->name = $name;
class Car
}
{ function get_name()
// Properties {
public $name; return $this->name;
public $color; }
}
?>

152
Accessing Property and Method:-
• Once we have created Object we can •Example1:-
use the -> (object operator) to
access property and method of the
<?php
object. class Student
•Syntax:- {
var $roll_no;
$object->property_name; var $name;
function display()
$object->method_name([arg,…..]); {
echo “Roll No:” . $this->roll_no .
“<br>”
153
Accessing Property and Method:-
echo “Name:” . $this-> name; •Example2:-
} <?php
class Fruit
}
{
$s1 = new Student; // Properties
$s1 -> roll_no =12; public $name;
$s1 -> name = “Ram”; public $color;
$s1 -> display();
// Methods
?> function set_name($name) {
Output:- Roll No: 12 $this->name = $name;
Name: Ram }

154
Accessing Property and Method:-
function get_name() { echo $apple->get_name();
return $this->name; echo "<br>";
} echo $banana->get_name();
} ?>

$apple = new Fruit(); Output:-


$banana = new Fruit(); Apple
$apple->set_name('Apple'); Banana
$banana->set_name('Banana');

155
Accessing Property and Method:-
Example:- // Method to get the area
<?php public function getArea(){
class Rectangle
{
return ($this->length * $this-
// Declare properties
>width);
public $length = 0; }
public $width = 0; }
// Create a new object from
// Method to get the perimeter Rectangle class
public function getPerimeter(){ $obj = new Rectangle;
return (2 * ($this->length + $this-
>width)); // Get the object properties values
} echo $obj->length;
156
Accessing Property and Method:-
echo $obj->width; // Call the object methods
echo “Perimeter:” . $obj-
// Set object properties values >getPerimeter() . “<br>”;
$obj->length = 30; echo “Area” . $obj->getArea();
$obj->width = 20; ?>
Output:- Perimeter: 100
// Read the object properties values
again to show the change Area: 600
echo $obj->length;
echo $obj->width;

157
Differences:
this
- self •this keyword should be preceded
•Self keyword is not preceded by with a $ symbol.
any symbol. •-> symbol is used with $this as we
•To access class variable and have used with an object to access
method using the self keyword, we the property of that object.
use scope resolution operator :: •It is refer to the non static member
•It is refer to the static member of of class with -> operator.
class. •Example:- $this -> <class_member>
•Example:- self::<class_member>

158
construct Function in PHP:
Example:-
-•A constructor allows you to class MyClass
initialize an object's properties
upon creation of the object. {
•If you create a construct()function, function_construct()
PHP will automatically call this {
function when you create an echo “Welcome to PHP constructor.
object from a class.
<br>”;
•Notice that the construct function
starts with two underscores ( )! }
•Constructor saves us from calling }
the set_name() method which $obj = new Myclass;
reduces the amount of code.
159
construct Function in PHP:
function Sample()
- Constructor Type:- {
• Default Constructor:- echo “Its a user define constructor of
• It has no parameters, but the value the class Sample. <br>”;
to the default constructor can be }
pass dynamically. function construct()
• We can define constructor by using {
function construct() echo “Its a Pre-define constructor of the
class Sample. <br>”;
Example:-
}
<?php
}
class Sample $obj = new Sample; ?>
{
160
construct Function in PHP:
private lname;
- Constructor Type:- public function construct($fname,
• Parameterized Constructor:- $lname)
• It take the parameters and you can
pass the value to the data member. {
• It is use to initialize member variable echo “Initializing the object…. <br>”;
at the time of object creation. $this->fname = $fname;
• -> operator is use to set value for
variable. $this->lname = $lname;
Example:- }
<?php public function showName()
class emp
{
{
private $fname;
161
construct Function in PHP:
Example2:-
- echo “ My name is “. Mr.” . $this- <?php
>fname . “ ” . this->lname; class Fruit {
} public $name;
} public $color;
$e1 = new emp ( “Ram”, “Mishra”); function construct($name, $color)
e1->showName(); {
Output:- $this->name = $name;
Initializing the object…. $this->color = $color;
My name is Mr. Ram Mishra }

162
construct Function in PHP:
$apple = new Fruit("Apple", "red");
- function get_name() echo $apple->get_name();
{ echo $apple->get_color();
echo “ $this->name is”; ?>
}
function get_color() Output:- Apple is Red
{
return $this->color;
}
}
163
destruct Function in PHP:
-• A destructor is called when the Syntax:-
object is destructed or the script is function_destruct()
stopped or exited.
{
• If you create a destruct() function,
PHP will automatically call this
function at the end of the script. }
•Notice that the destruct function
starts with two underscores ( )!
•A destruct() function that is
automatically called at the end of
the script.

164
destruct Function in PHP :
$this->fname = $fname;
- Example:- $this->lname = $lname;
<?php }
class emp public function destruct()
{ {
Private $fname; echo “Destroying Objrct…..”;
private lname; }
public function construct($fname, public function showName()
$lname) {
{
echo “Initializing the object…. <br>”;
165
destruct Function in PHP :
- echo “ My name is “. Mr.” . $this- Example2:-
>fname . “ ” . this->lname; <?php
} class Fruit {
} public $name;
$e1 = new emp ( “Ram”, “Mishra”); public $color;
e1->showName(); function construct($name, $color)
Output:- {
Initializing the object…. $this->name = $name;
My name is Mr. Ram Mishra }
Destroying Objrct…..
166
destruct Function in PHP :
 Advantages of destruct
- function destruct() function:-
{ •Destructor is used to free up
memory allocation, so that space
echo "The fruit is {$this- is available for new object or free
>name}."; up resources for other task.
}
} •It effectively make programs run
$apple = new Fruit("Apple"); more efficiently and is very
useful as they carry clean up
?> tasks.
Output:- This fruit is Apple
167
Inheritance in PHP:
The new sub class.
-•Inheritance in OOP = When a •Syntax:-
class derives from another class. class Parent
•The child class will inherit all the {
public and protected properties
and methods from the parent // parent class code
class. In addition, it can have its }
own properties and methods. class Child extends Parent
•An inherited class is defined by {
using the extends keyword.
// The child can be use the
•We create a new sub class with parent class code }
all functionality of that existing
class, and we add ne member to 168
Inheritance in PHP :
- Example 1:- }}
<?php Class Rect extends Shape
class Shape {
{
public $height;
public $length;
public $width;
public function construct($length,
public function construct($length,
$width, $height)
$width) {
{ $this->length = $length;
$this->length = $length; $this->width = $width;
$this->width = $width;
$this->height = $height;
169
Inheritance in PHP :
- }
public function intro() Output:-
{ The length is 10, the width is 20 and
echo "The length is {$this->length}, the height is 30
the width is {$this->width} and the
height is {$this->height} ";
}
}
$r = new Rect( 10, 20, 30)
$r-> intro();
?>

170
Inheritance in PHP :
}
- Example 2:- public function intro()
<?php {
class Shape echo "The length is {$this->length} and
the width is {$this->width} ";
{ }}
public $length; Class Rect extends Shape
public $width; {
public function construct($length, public $height;
$width) public function construct($length,
$width, $height)
{ {
$this->length = $length; $this->length = $length;
$this->width = $width;
171
Inheritance in PHP :
- $this->width = $width;
$r-> intro();
$this->height = $height;
$r-> introduction();
}
protected function introduction()
?>
{
echo "The length is {$this->length}, Output:-
the width is {$this->width} and the The length is 10 and the width is 20
height is {$this->height} ";
}
Fatal error
}
$r = new Rect( 10, 20, 30);

172
Inheritance in PHP : }
- Example 3:- protected function intro()
<?php {
class Shape echo "The length is {$this->length}
and the width is {$this->width} ";
{
}}
public $length;
Class Rect extends Shape
public $width;
{
public function construct($length,
$width)
public function introduction()
{
{
echo “The shape is Rectangle”;
$this->length = $length;
$this->width = $width;
173
Inheritance in PHP :
 Type of Inheritance:-
- $this->intro(); •Single Inheritance:-
} When a subclass is derived simply
} from its parent class then this
mechanism is known as Simple
$r = new Rect( 10, 20, 30); inheritance or Single or one level
$r-> introduction(); Inheritance.
?> A
Output:-
The shape is Rectangle. The length is
10 and the width is 20 B
174
Inheritance in PHP : •Multilevel Inheritance:-
- • Syntax:- When a subclass is derived from a
class Parent derived class then this mechanism is
known as the multilevel Inheritance.
{
// parent class code
} A
class Child extends Parent
{
B
// The child can be use the parent
class code
} C
175
Inheritance in PHP :
• Example:-
- • Syntax:- <?php
class A class grandparent
{ {
function level1()
}
{
class B extends A
echo “ Grand-Parent <br>”;
{
}}
} class parent extends grandparent
class C extends B {
{ function level2()
}
176
Inheritance in PHP :
- {
echo “Parent <br>”; $obj = level1();
}} $obj = level2();
class child extends parent $obj = level3();
{ ?>
function level3()
{ Output:-
echo “ Child <br>”; Grand-Parent
}} Parent
$obj = new child() Child

177
Inheritance in PHP : •Example:-
- •Hierarchical Inheritance:- <?php
• Hierarchical Inheritance consist of {
Single parent class and is inherited by public function f_a()
multiple child class.
{
• In this type one class is extended by
many subclasses.
echo “class A”;
• It is one-to-many relationship.
}
A
}
class b extends a
{
B C D
178
Inheritance in PHP :
}
- public function f_b() }
{ echo c::f_c(). “<br>”;
echo “class B”; echo c::f_a()
} ?>
}
class c extends a Output:-
{ class C
public function f_c() Class A
{
echo “class C”;
179
Method or Function Overloading in PHP:-
•If the derived class is having a Example:-
same method name as the base <?php
class then the method in the
derived class take precedence class Base
over or overrides the base class {
method
function show()
•Function overloading or method
overloading is the ability to {
create multiple function of the echo “Display Base <br>”;
same name with different
implementation depending on }
types of their requirement. }
180
Method or Function Overloading in PHP :-
class Derived extends Base •Output:- Display Derived
{ •To call base class show() method
function show() we can use parent::method();
•Scope resolution operator (::) is
{ used to refer function and variable
echo “Display Derived”; in base class.
} function show()
} {
$obj = new Derived(); parent::show();
$obj = show(); echo “Display Derived”;
?> }

181
Method or Function Overriding in PHP:-
•In function overriding, both Example:-
parent and child classes should <?php
have same function name with class P
and number of arguments. {
•It is used to replace parent function geeks()
method in child class.
{
•The purpose of overriding is to echo "Parent";
change the behavior of parent
class method. }
•The two methods with the same }
name and same parameter is class C extends P
called overriding. {
182
Method or Function Overriding in PHP:-
function geeks() •Output:- Parent
{ Child
echo "\nChild";
•When a method or a class is
} declared as final then overriding
} on that method or class cannot
$p = new P; be performed also inheritance
$c= new C; with the class is not possible.
$p->geeks();
$c->geeks();
?>

183
Class Overriding using Final Keyword:-
Example:- echo "<br> In the BaseClass Method
final class BaseClass display function";
{ // here you cannot extend the base class }
// as the base class is declared as final }
function ABC() $obj1 = new BaseClass;
{ $obj1->display();
echo "<br> In the BaseClassMethod $obj1->ABC();
ABC function"; Output:-
}
In the BaseClass Method ABC function
function display()
In the BaseClass Method display function
{

184
Method Overriding using Final Keyword :-
Example:- echo "<br /> In the Base cLass ABC
class BaseClass function";
{ // Final method – display }
// this cannot be overridden in base class }
final function display() class DerivedClass extends BaseClass
{ {
echo "<br /> In the Base class function ABC()
display function"; {
} echo "<br /> In the Derived class ABC
function";
function ABC() }
{ }

185
Method Overriding using Final Keyword :-
 Cloning Object:-
$obj1 = new DerivedClass; •Object cloning is the process in
$obj1->display(); PHP to create a copy of an object.
$obj1->ABC(); •An object copy is created by using
the clone keyword.
Output:- •When an object is cloned, PHP will
perform a shallow copy of all
In the Base class display function object property.
In the Derived class ABC function
•Syntax:-$copy_object_name =
clone $object to_be_copied

186
Cloning Object :-
$obj->amount = 5;
Example:- $copy = clone $obj;
<?php print_r($copy);
class MyClass ?>
{
• Output:-
public $color;
MyClass Object ([color] => red
public $amount; [amount] => 5)
}
$obj = new MyClass();
$obj->color = 'red';
187
clone() method to break references:-
Example:- $value = 5;
<?php $obj = new MyClass();
class MyClass { $obj->amount = &$value;
public $amount; $copy = clone $obj;
public function clone() $obj->amount = 6;
{ print_r($copy);
$value = $this->amount; ?>
unset($this->amount); Output:-
$this->amount = $value; MyClass Object ([amount] => 5)
} } // or $amount = $value;

188
Introspection in PHP:
•You don’t need to know which
-•Introspection is the ability of a methods or properties are
program to examine an object’s defined when you write your
characteristics, such as its name, code.
parent class (if any), properties, •Instead, you can discover that
and methods. information at runtime, which
•PHP offers a large number of makes it possible for you to write
functions that you can use to generic debuggers, serializes,
accomplish the task. profilers.
•With introspection, you can
write code that operates on any
class or object. 189
Introspection in PHP:-

190
Introspection :
- Example1:-
}
<?php
?>
if(class_exists(‘GPG'))
{
$obj =new GPG(); Output:- Not exist
echo "This is www.gpg.ac.in";
}
else
{
echo "Not exist";

191
Introspection :-
else
Example2:-
<?php {
class GPG echo "Not exist";
{ }
//decl
?>
}
if(class_exists(‘GPG'))
{ Output:- This is www.gpg.ac.in
$obj =new GPG();
echo "This is www.gpg.ac.in";
}
192
Introspection :
- Example3:-
print_r($class_method);
<?php ?>
class GPG
{
Output:- Array ([0]=> co [1]=> it)
function co() {}
Function it() {}
}
$obj =new GPG();
$class_methods =
get_class_method(‘GPG’);
193
Serialization and unserialization in PHP:
- •Serialization is a technique used
by programmer to preserve •Example:-
their working data in a format <html>
that can later be restore to its <body>
previous form. $s_data = serialize(array("Red",
<?php
"Green", "Blue"));
•Sterilizing object means echo $s_data;
converting it to byte stream $us_data = unserialize($s_data) ;
representation that can stored echo $us_data;
in a file. ?>
•Serialization in PHP is mostly </body></html>
automatic process.
194
Serialization in PHP: •Example 2:-
- •Output:- <?php
a:3:{i:0;s:3:"Red";i:1;s:5:"Green"; class Student
i:2;s:4:"Blue";} $age = 19;
Array ([0]=>Red [1]=>Green function show_Age()
[2]=>Blue
{
echo $this->age;
}
}
195
Serialization in PHP:
-
$stud = new Student;
Sstud->show_Age();
$s_obj = serialize($stud);
$fp = fopen(“gpg.txt”, “w”);
fwrite($fp, $s_obj);
fclose($fp);
$us_obj = unserialize($s_obj);
$us_obj->show_Age();
?>
196
Happy
Learning
Thank You
!

197

198
199
201
206
209
210

211
215
216

217
277
281

You might also like