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

PHP Chapter2

The document outlines a course on Web Based Application Using PHP, focusing on operations with arrays and graphics. It covers various types of arrays, including indexed, associative, and multidimensional arrays, along with functions like implode and explode for manipulating array data. Additionally, it discusses traversing arrays, deleting elements, and sorting methods to enhance data organization and retrieval.

Uploaded by

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

PHP Chapter2

The document outlines a course on Web Based Application Using PHP, focusing on operations with arrays and graphics. It covers various types of arrays, including indexed, associative, and multidimensional arrays, along with functions like implode and explode for manipulating array data. Additionally, it discusses traversing arrays, deleting elements, and sorting methods to enhance data organization and retrieval.

Uploaded by

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

Program: Computer Engineering

Course Name: Web Based Application Using PHP

Course Code: 22619

Course Outcome: Perform Operations based on arrays and graphics

Unit Outcomes: a) Manipulate given type of arrays to get the desired result
b)Apply implode and explode function on the given array
c)Apply the given string functions on the character array.
d)Scale the given image using graphics concepts/ functions.
Learning Outcome 2 :
Student should understand basic concepts of Array
and graphics
What we
What we willwill
learnlearn
today today

► Array, types of array


► Explode and implode function in array.
► Function and its types
► Operations on String and String functions
► Graphis concepts
Concept Map
Array

 Arrays in PHP is a type of data structure that allows to store multiple elements of similar data type
under a single variable thereby saving us the effort of creating a different variable for every data.
 An array in PHP is actually an ordered map. A map is a type that associates values to keys.
 The arrays are helpful to create a list of elements of similar types, which can be accessed using
their index or key.
 Suppose we want to store five names and print them accordingly. This can be easily done by the
use of five different string variables. But if instead of five, the number rises to hundred, then it
would be really difficult for the user or developer to create so much different variables. Here array
comes into play and helps us to store every element within a single variable and also allows easy
access using an index or a key.
 An array is created using an array() function in PHP.
Types of Array :

►Indexed or Numeric Arrays


►Associative Arrays
►Multidimensional Arrays

5
Indexed or Numeric Arrays

 An array with a numeric index where values are stored linearly.


 Numeric arrays use number as access keys.
 An access key is a reference to a memory slot in an array variable.
 The access key is used whenever we want to read or assign a new value an array
element.
 Syntax
 <?php
 $variable_name[n] = value;
 ?>
 OR
 <?php
 $variable_name = array(n => value, …);
6
 ?>
<html>
<head>
<title>
array
</title>
</head>
<body>
Output:
<h1> Creating an array </h1>
<?php
$course[0]="Computer Engg.";
Creating an array
$course[1]="Information Tech."; Electronics and Telecomm.
$course[2]="Electronics and Telecomm.";
Computer Engg.
// Accessing the elements directly Information Tech.
echo $course[2], "<BR>";
echo $course[0], "<BR>";
echo $course[1], "<BR>";

?>
7
</body>
</html>
<html>
<head>
<title>
array
</title>
</head> Output:
<body>

<h1> Creating an array </h1> Creating an array


<?php Information Tech.
$course = array(0 => "Computer Engg.",1 => "Information
Tech.", 2 => "Electronics and Telecomm.");

echo $course[1];
?>
</body>
</html> 8
Associative Arrays

► This type of arrays is similar to the indexed arrays but instead of linear storage, every value can be
assigned with a user-defined key of string type.
► An array with a string index where instead of linear storage, each value can be assigned a specific key.
► Associative array differ from numeric array in the sense that associative arrays use descriptive names
for id keys.
Syntax :

<?php
$variable_name['key_name'] = value;

$variable_name = array('keyname' => value);


?>

9
<?php
$capital = array("Mumbai" => "Maharashtra","Goa" => "Panaji", "Bihar" =>
"Patna");

print_r($capital);
echo"<br>";

echo "Mumbai is a capital of " .$capital ["Mumbai"];


?>
By default, array starts with index 0. What if you wanted to start
with index 1 instead? You could use the
PHP =>operator like this:
$course = array ( 1 => "Computer Engg.",
2 => "Information Tech.",
3 => "Electronics and Telecomm.");
The => operator create key/value pairs in arrays-the item on the
left of the operator => is the key and the item on the right is the
value.
11
<html>
<head>
<title>
array
</title>
</head>
<body>
<h1> Creating an array </h1>
<?php
$course = array(1 => "Computer Engg.", 5 => "Information Tech.", 3 => "Electronics and
Telecomm.");
echo $course [5];
?>
</body>
</html>
12
<?php

$course = array("CO"=>549,
"IF"=>450,
"EJ"=>100);

echo "course['CO']=", $course["CO"],"<br>";


echo "course['IF']=", $course["IF"],"<br>";
echo "course['EJ']=", $course["EJ"],"<br>";
?>
13
Multidimensional Arrays
• These are arrays that contain other nested arrays.
• An array which contains single or multiple arrays within it and can be accessed via multiple
indices.
• We can create one dimensional and two-dimensional array using multidimensional arrays.
• The advantage of multidimensional arrays is that they allow us to group related data
together.
Syntax:
array (
array (elements...),
array (elements...),
...
) 14
<?php
// Defining a multidimensional array
$person = array(
array(
"name" => "Yogita K",
"mob" => "5689741523",
"email" => "[email protected]",
),
array(
"name" => "Manisha P.",
"mob" => "2584369721",
"email" => "[email protected]",
),
array(
"name" => "Vijay Patil",
"mob" => "9875147536",
"email" => "[email protected]",
)
);

// Accessing elements
echo "manisha P's email-id is: " . $person[1]["email"], "<br>";
echo "Vijay Patil's mobile no: " . $person[2]["mob"];

?>
<?php
$mobile = array
(
array("LG",20,18),
array("sony",30,13),
array("Redme",10,2),
array("Samsung",40,15)
);
echo $mobile[0][0].": In stock: ".$mobile[0][1].", sold: ".$mobile[0][2].".<br>";
echo $mobile[1][0].": In stock: ".$mobile[1][1].", sold: ".$mobile[1][2].".<br>";
echo $mobile[2][0].": In stock: ".$mobile[2][1].", sold: ".$mobile[2][2].".<br>";
echo $mobile[3][0].": In stock: ".$mobile[3][1].", sold: ".$mobile[3][2].".<br>";
?>

Output:

LG: In stock: 20, sold: 18.


sony: In stock: 30, sold: 13.
Redme: In stock: 10, sold: 2.
Samsung: In stock: 40, sold: 15.
Implode and Explode
1) Implode()
► The implode() is a built-in function in PHP and is used to join the elements of an array.
► The implode() function returns a string from the elements of an array.
► If we have an array of elements, we can use the implode() function to join them all to form one string. We
basically join array elements with a string. Just like join() function , implode() function also returns a string
formed from the elements of an array.

Syntax :
string implode(separator, array);
 The implode() function accepts two parameter out of which one is optional and one is mandatory.
 separator : This is an optional parameter and is of string type. The values of the array will be join to form a string
and will be separated by the separator parameter provided here. This is optional, if not provided the default is “”
(i.e. an empty string).
 array : The array whose value is to be joined to form a string.
<html>
<head>
<title>
array
</title>
</head>
<body>
Output:
<h3> Extracting variables from array </h3>
<?php Extracting variables from array
$course[0]="Computer Engg."; Computer Engg., Information Tech., Electronics
$course[1]="Information Tech."; and Telecomm
$course[2]="Electronics and Telecomm.";
$text=implode(",",$course);
echo $text;
?>
</body>
</html>
<?php
// PHP Code to implement join function
$InputArray = array('CO','IF','EJ');

// Join without separator Output:


print_r(implode($InputArray));
print_r("<BR>"); COIFEJ
CO-IF-EJ
// Join with separator
print_r(implode("-",$InputArray));
?>
2) Explode()
 The explode() function breaks a string into an array.
 The explode() is a built in function in PHP used to split a string in different strings.
 The explode() function splits a string based on a string delimeter, i.e. it splits the string wherever the
delimeter character occurs. This function returns an array containing the strings formed by splitting
the original string.
Syntax :
array explode(separator, OriginalString, NoOfElements);
► The explode( )function accepts three parameters of which two are compulsory and one is optional. All the three
parameters are described as follows :
1.separator : This character specifies the critical points or points at which the string will split, i.e. whenever this
character is found in the string it symbolizes end of one element of the array and start of another.
2.OriginalString : The input string which is to be split in array.
3.NoOfElements : This is optional. It is used to specify the number of elements of the array. This parameter can be
any integer ( positive , negative or zero)
(i)Positive (N) : When this parameter is passed with a positive value it means that the array will contain this number
of elements. If the number of elements after separating with respect to the separator emerges to be greater than
this value the first N-1 elements remain the same and the last element is the whole remaining string.
(ii)Negative (N) : If negative value is passed as parameter then the last N element of the array will be trimmed out
and the remaining part of the array shall be returned as a single array.
(iii)Zero : If this parameter is Zero then the array returned will have only one element i.e. the whole string.
► When this parameter is not provided the array returned contains the total number of element formed after
separating the string with the separator.
<html>
<body>
<?php
$str = "PHP: Welcome to the world of PHP";
print_r (explode(" ",$str));
?>
</body>
</html>

Output:

Array ( [0] => PHP: [1] => Welcome [2] => to [3] => the [4] => world [5] => of [6] => PHP )
Array_flip()
► The array_flip() function flips/exchanges all keys with their associated values in an
array.
► This built-in function of PHP array_flip() is used to exchange elements within an
array, i.e., exchange all keys with their associated values in an array and vice-versa.
►Syntax :
array_flip(array);
<html>
<body>
<?php
$a1=array("CO"=>"Computer Engg","IF"=>"Information Tech","EJ"=>"Electronics and Telecomm");
$result=array_flip($a1);
print_r($result);
?>
</body>
</html>

Output:

Array ( [Computer Engg] => CO [Information Tech] => IF [Electronics and Telecomm] => EJ )
Traversing Arrays
►Traversing an array means to visit each and every element of
array using a looping structure and iterator functions.
►There are several ways to traverse arrays in PHP.
1. Using foreach Construct: PHP provides a very special kind of looping statement
called foreach that allows us to loop over arrays. The foreach statement only works
with arrays and objects.

<?php
$a = array(‘aaa’, ‘bbb’, ‘ccc’);
foreach($a as $value) Output:
{ aaa
echo “$value\n”; bbb
} ccc
?>

2. In the above foreach loop, the loop will be executed once for each element of $a, i.e. three times.
And for each iteration $value will store the current element.
<?php
$a=array(‘one’ ⇒ 1, ‘two’ ⇒ 2, ‘three’ ⇒ 3);
Output:
foreach ($a as $k ⇒ $v)
{ one is 1
echo “$k is $v \n”; two is 2
} three is 3
?>

► In this case the key for each element is stored in $k and the corresponding value is
stored in $v. The foreach operates on copy of array, not on array itself.
2. Using a for Loop:
The for loop operates on the array itself, not on a copy of the array.

<?php
$a = array(1, 2, 3, 4); Output:
1
for($i=0; $i<count($a); $i++) 2
{ 3
echo $a[i] . “<br>”; 4
}
?>
Deleting Array Elements

►The unset() function is used to remove element from the array.


The unset() function is used to destroy any other variable and
same way use to delete any element of an array.
►The unset () function accepts a variable name as parameter
and destroy or unset that variable
►Syntax :
void unset ($var,...);
<?php

$course = array("CO", "IF", "EJ", "ME", "CE");


echo "<h2> Before deletion:</h2><br>";
echo "$course[0] <br>"; Output:
echo "$course[1] <br>";
echo "$course[2] <br>"; Before deletion:
echo "$course[3] <br>"; CO
echo "$course[4] <br>"; IF
// unset command accepts 3rd index and thus removes the EJ
array element at ME
CE
// that position
Before deletion:
unset($course[3]);
echo "<h2> Before deletion:</h2><br>"; Array ( [0] => CO [1] => IF [2] => EJ [4] => CE )
print_r($course); Delete entire array elements:
echo "<h2> Delete entire array elements:</h2><br>";
unset($course); //delete all elements from an array
?>
Sorting Arrays
► Sorting refers to ordering data in an alphabetical, numerical order and increasing or
decreasing fashion according to some linear relationship among the data items
depends on the value or key. Sorting greatly improves the efficiency of searching.
► Following are the Sorting Functions for Arrays in PHP :
1. sort(): sorts arrays in ascending order
2.rsort(): sorts arrays in descending order
3.asort(): sorts associative arrays in ascending order, according to the value
4.ksort(): sorts associative arrays in ascending order, according to the key
5.arsort(): sorts associative arrays in descending order, according to the value
6.krsort(): sorts associative arrays in descending order, according to the key
<?php
$num = array(40, 61, 2, 22, 13);
echo "Before Sorting:<br>";
$arrlen= count($num);
for($x = 0; $x < $arrlen; $x++)
{ Output:
echo $num[$x];
echo "<br>"; Before Sorting:
40
} 61
sort($num); 2
echo "After Sorting in Ascending order:<br>"; 22
$arrlen= count($num); 13
for($x = 0; $x < $arrlen; $x++) After Sorting in Ascending order:
{ 2
echo $num[$x]; 13
22
echo "<br>"; 40
} 61
echo "After Sorting in Descending order:<br>"; After Sorting in Descending order:
rsort($num); 61
$arrlen= count($num); 40
for($x = 0; $x < $arrlen; $x++) 22
{ 13
2
echo $num[$x];
echo "<br>";
}
?>
► The following function sorts an associative array in ascending order, according to the
value by using asort() and key by using ksort() :
<?php
$percent = array("Manisha"=>"80", "Yogita"=>"78",
"Siddhesh"=>"68");
echo "<b>Sorting according to Value:</b><br>"; Output :
asort($percent);
foreach($percent as $x => $x_value) Sorting according to Value :
{ Key=Siddhesh, Value=68
echo "Key=" . $x . ", Value=" . $x_value; Key=Yogita, Value=78
echo "<br>"; Key=Manisha, Value=80
}
Sorting according to Key :
echo "<br><br><b>Sorting according to Key:</b><br>";
ksort($percent); Key=Manisha, Value=80
foreach($percent as $x => $x_value) Key=Siddhesh, Value=68
{ Key=Yogita, Value=78
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Splitting and Merging Arrays
► You can also cut up and merge arrays when needed. For example, say you have 5 courses in array of course and want to get a
subarray consisting of the last two items. You can do this with the array_slice() function, passing it the array you want to get a
section of, the offset at which to start and the length of the array you want to create.
► Syntax :
►array_slice(array, start, length, preserve) ;
► Where,
► Array : Specifies an array and this is required parameter.
► start : This is required parameter and contain numeric value. Specifies where the function will start the slice. 0 = the first
element. If this value is set to a negative number, the function will start slicing that far from the last element.
► -2 means start at the second last element of the array.
► Length : This is optional parameter and contain numeric value. Specifies the length of the returned array. If this value is set to a
negative number, the function will stop slicing that far from the last element. If this value is not set, the function will return all
elements, starting from the position set by the start-parameter.
► Preserve: This is optional parameter. Specifies if the function should preserve or reset the keys. Possible values :
► o true - Preserve keys
► o false - Default Reset keys
<?php
$course[0] = "Computer Engg";
$course[1] = "Information Tech";
$course[2] = "Electronics and Telecomm";
echo "<h2> Before Splitting array:</h2>";

echo $course[0], "<BR>";


echo $course[1], "<BR>";
echo $course[2], "<BR>"; Before Splitting array:
Computer Engg
echo "<br><h2>After Splitting:</h2>"; Information Tech
Electronics and Telecomm
$subarray = array_slice($course, 1, 2); After Splitting:
foreach ($subarray as $value) Course: Information Tech
{ Course: Electronics and Telecomm
echo "Course: $value<br>";
}

?>
►You can also merge two or more arrays with array_merge():

<?php
$sem3 = array("Object Oriented Programming", "Principle
of Database", "Data Structure"); Output :
$sem4 = array("Database Management", "Java Subject: Object Oriented Programming
Programming", "Software Engg.", "Computer Network"); Subject: Principle of Database
Subject: Data Structure
$subject = array_merge($sem3, $sem4); Subject: Database Management
Subject: Java Programming
foreach ($subject as $value) Subject: Software Engg.
{ Subject: Computer Network
echo "Subject: $value<br>";
}
?>
PHP Array Functions
Function Description Syntax Example
Array_diff() Compare the values of two array_diff(array1, array2, $a1=array('PHP','C','Java','Perl');
arrays, and return the array3, ...) $a2=array('PHP’, 'Java');
differences.
array_diff($a1,$a2);
output :
Array ( [1] => C [3] => Perl )

Array_intersect() Compare the values of two array_intersect(array1, $a1=array('PHP','C','Java','Perl');


arrays, and return the array2, array3, ...) $a2=array('PHP','ASP','Java','Python');
matches
array_intersect($a1,$a2);
output :
Array ( [0] => PHP [2] => Java )

Array_chunk() Split an array into chunks of array_chunk(array, size, $a1=array('PHP','C','Java','Perl');


two and preserve the preserve_key) $ac=array_chunk($a1,2,true);
original keys
Output :
Array ( [0] => Array ( [0] => PHP [1] => C ) [1] =>
Array ( [2] => Java [3] => Perl ) )
Function Description Syntax Example
Array_combine() Create an array by using the array_combine(keys, values) $a1=array("PHP","Java","Perl");
elements from one "keys" $a2=array("10","20","30");
array and one "values"
array $ac=array_combine($a1,$a2);
Output :
Array ( [PHP] => 10 [Java] => 20 [Perl] => 30 )

Array_unique() Remove duplicate values array_unique(array, $a1=array("10","20","30","20");


from an array sorttype) $ac=array_unique($a1);
Output :
Array ( [0] => 10 [1] => 20 [2] => 30 )

Array_count_values Count all the values of an array_count_values(array) $a1=array("10","20","30","20");


() array print_r(array_count_values($a1));
Output :
Array ( [10] => 1 [20] => 2 [30] => 1 )
Function Description Syntax Example

Array_merge() Merge two arrays into one array_merge(array1, $a1=array("10","20");


array array2, array3, ...) $a2=array("30","40");
print_r(array_merge($a1,$a2));
Output :
Array ( [0] => 10 [1] => 20 [2] => 30 [3] =>
40 )
Array_pop() Delete the last element of array_pop(array) $a1=array("10","20","30");
an array array_pop($a1);
Output :
Array ( [0] => 10 [1] => 20 )

Array_product() Calculate and return the array_product(array) $a1=array(10,20);


product of an array echo(array_product($a1));
Output : 200
Function Description Syntax Example
Array_push() Inserts one or more array_push(array, value1, $a1=array(10,20);
elements to the end of value2, ...) array_push($a1,"PHP","Perl");
an array.
Output :
Array ( [0] => 10 [1] => 20 [2] => PHP [3]
=> Perl )

Array_reverse() Return an array in the array_reverse(array, $a1=array("a"=>"PHP",


reverse order preserve) "b"=>"Java","c"=>"Perl");
print_r(array_reverse($a1));
Output :
Array ( [c] => Perl [b] => Java [a] => PHP )
Array_search() Searchs an array for a array_search(value, array, $a1=array("a"=>"PHP",
value and returns the strict) "b"=>"Java","c"=>"Perl");
key echo(array_search("Java",$a1));
output : b
Function Description Syntax Example
Array_sum() Return the sum of all array_sum(array) $a1=array(10,20,30);
the values in the echo(array_sum($a1));
array
output : 60

Count() Returns the number of count(array) $a1=array(10,20,30);


elements in an array echo(count($a1));
output : 3
Functions and Its Types
► PHP functions are similar to other programming languages. A function is a piece of
code which takes one more input in the form of parameter and does some
processing and returns a value.
► They are built-in functions, but PHP gives you option to create your own functions as
well. A function will be executed by a call to the function. You may call a function
from anywhere within a page.
Syntax :
function functionName()
{
code to be executed;
}
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>

<?php
/* Defining a PHP Function */ Output :
function writeMessage()
{ Welcome to PHP world!
echo "Welcome to PHP world!";
}

/* Calling a PHP Function */


writeMessage();
?>
</body>
</html>
PHP Functions with Parameters :

<?php
function addfunc($num1, $num2)
{ Output:
$sum = $num1 + $num2; Sum of the two numbers is : 70
echo "Sum of the two numbers is :
$sum";
}
addfunc(50, 20);
?>
PHP Functions returning value :

<?php
function add($num1, $num2)
{ Output:
$sum = $num1 + $num2;
return $sum; Returned value from the function : 70
}
$return_value = add(50, 20);
echo "Returned value from the
function : $return_value";
?>
Variable Function
► PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to
it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to
execute it. Among other things, this can be used to implement callbacks, function tables and so forth.

<?php
function
{
echo “ PHP is grt”; Output :
}
$ func=“wow”; PHP is grt
$func();
?>wow()
<?php
function wow($ name)
{ Output :
echo “ Hello $ name”;
} Hello Google
$ func=“wow”;
$func(“Google”);

?> ► Above example uses is_callable() function


to verify whether the parameter is a
function or not.
Anonymous or Lambda Function
► There are times when you need to create a small localized throw-away function consisting of a few
lines for a specific purpose, such as a callback. It is unwise to pollute the global namespace with
these kind of single use functions. For such an event you can create anonymous or lambda
functions using create_function (). Anonymous functions allow the creation of functions which
have no specified name.
<?php
$sayhello=function($name)
Output :
{
Echo “hello $name”; hello google
};
$sayhello (“Google”);
?>
► Here we have created a small nameless (Anonymous) function which is used as a callback in the
preg_replace_callback( ) function. preg_replace_callback( ) — Perform a regular expression search and
replace using a callback.
► Although create_function lets you create anonymous functions. We create an unnamed function and assign it
to a variable, including whatever parameters the functions accept and then simply use the variable like an
actual function.
Operations on String and String Functions
► A string is a collection of characters. String is one of the data types supported by PHP.
► The string variables can contain alphanumeric characters.
► Creating a string : There are 2 ways to create a string in php.
(i) Creating Strings Using Single quotes: The simplest way to create a string is to use
single quotes. Let’s look at an example that creates a simple string in PHP.

Output:
<?php
string(22) "PHP is string-oriented"
var_dump(‘PHP is string-oriented’);
?>
(ii) PHP Create Strings Using Double quotes
► The double quotes are used to create relatively complex strings compared to single
quotes.
► Variable names can be used inside double quotes and their values will be displayed.

<?php
$name='PHP'; Output :
echo "$name is string-oriented"; PHP is string-oriented
?>
Converting to and from Strings
► Because data is sent to you in string format, and because you will have to display your data in string
format in the user’s browser, converting between strings and numbers is one of the most important
interface tasks in PHP.
(i) Using number_format() Function :
The number_format () function is used to convert string into a number.
It returns the formatted number on success otherwise it gives E_WARNING on failure.
<?php
$num = "20100.3145";
// Convert string in number using
number_format()
echo number_format($num), "<br>"; Output :
// Convert string in number using 20,100
number_format() 20,100.315
echo number_format($num, 3);
?>
(ii) Using type casting :
► Typecasting can directly convert a string into float, double or integer primitive type.
This is the best way to convert a string into number without any function.

<?php

// Number in string format


$num = "20100.3145";

// Type cast using int Output :


echo (int)$num, "<br>"; 20100
20100.3145
// Type cast using float 20100.3145
echo (float)$num, "<br>";

// Type cast using double


echo (double)$num;
?>
(iii)Using intval() and floatval() Function :
The intval() and floatval() functions can also be used to convert the string into its
corresponding integer and float values respectively.

<?php
// Number in string format
$num = "1300.314"; Output :
// intval() function to convert string into integer
echo intval($num), "<br>"; 1300
// floatval() function to convert string to float 1300.314
echo floatval($num);
?>
String Functions
Function Description Syntax Example
str_word_count( ) Count the number of Str_word_count(String) <?php
words in a string echo str_word_count("Welcome
to PHP world!");
?>
Output:
4
strlen() Returns the length of a Strlen(String) <?php
string echo strlen("Welcome to PHP");
?>
Output: 14
strrev() Reverses a string Strrev(String) <?php
echo strrev("Information
Technology");
?>
Output:
ygolonhceT noitamrofnI
Function Description Syntax Example
strpos() Returns the position of the first occurrence Strops(String, text) <?php
of a string inside another string (case- echo strpos("PHP contains for
sensitive) loop, for each and while
loop","loop");
?>
Output:
17
str_replace() Replaces some characters in a string (case- Str_replace(string tobe <?php
sensitive) replaced, text, string) echo
str_replace("Clock","Click"
,"Click and Clock");
?>
Output:
Click and Click
Function Description Syntax Example
ucwords() Convert the first character of each word to Ucwords(String) <?php
uppercase echo ucwords("welcome to
php world");
?>

Output:
Welcome To Php World
strtoupper() Converts a string to uppercase letters Strtoupper(String) <?php
echo strtoupper("information
technology ");
?>
Output:
INFORMATION TECHNOLOGY

56
Function Description Syntax Example
strtolower() Converts a string to lowercase letters Strtolower(String) <?php
echo strtolower("INFORMATION
TECHNOLOGY");
?>
Output:
information technology

Str_repeat() Repeating a string with a specific Str_repeat(String, repeat) <?php


number of times. echo str_repeat("*",10);
?>
Output: **********

57
Function Description Syntax Example

strcmp() Compare two strings (case-sensitive). Strcmp(String1, String2) <?php


If this function returns 0, the two strings are echo strcmp("Hello world!","Hello world!");
equal. ?>
If this function returns any negative or Output:
positive numbers, the two strings are not
equal. 0

Another example:
<?php
echo strcmp(" world!","Hello PHP!");
?>
Output:
-40
Substr() substr() function used to display or extract a Substr(String, start, length) <?php
string from a particular position. echo substr("Welcome to PHP",11)."<br>";
echo substr("Welcome to PHP",0,7)."<br>";
?>
Output:
PHP
Welcome

58
Function Description Syntax Example
Str_split() To convert a string to an array str_split(string,length); $str=”PHP”
Str_split($str);

Output:
Array ( [0] => P [1] => H [2] => P )

Str_shuffle() To randomly shuffle all the character of a str_shuffle ( string $str ) $str=”PHP”
string Str_shuffle($str);
Output: PPH

59
Function Description Syntax Example
Trim() Removes white spaces and trim(string,charlist) $str=” Welcome “
predefined characters from a Output”
both the sides of a string.
Welcome

Rtrim() Removes the white spaces from end string rtrim ( string $str [, $str=”Hello PHP”
of the string string $character_mask ] Rtrim($str,”PHP”)
)
Output: Hello

60
Function Description Syntax Example
Ltrim() Removes the white spaces from ltrim(string,charlist); $str=“ PHP”
left side of the string Output: PHP

Chop() Remove whitespace or other chop(string,charlist); $str=”Hello PHP”


predefined character from Cho($str,”PHP”);
the right end of a string.
Output: Hello
Chunk_split() Splits a string into smaller parts chunk_split(string,length, $str=”Hello PHP”;
or chunks. end) Chunk_split($str,6,”…”);
Output: Hello… PHP…

61
PHP Maths Functions
Function Description Example
abs() Returns absolute value of given number. Abs(-7)= 7

ceil() Rounds fractions up. Ceil(3.3)=4


Ceil(-4.6)=-4
floor() Rounds fractions down. Floor(3.3)=3
Floor(-4.6)=-5
sqrt() Returns square root of given argument. Sqrt(16)=4

decbin() Converts decimal number into binary. It returns Decbin(2)=10


binary number as a string. Decbin(10)=1010

62
Function Description Example
dechex() Converts decimal number into hexadecimal. It Dechex(10)=a
returns hexadecimal representation of given Dechex(22)=16
number as a string.
decoct() Converts decimal number into octal. It returns Decoct(10)=12
octal representation of given number as a Decoct(22)=26
string.
bindec() Converts binary number into decimal. Bindec(10)=2
Bindec(1010)=10
sin() Return the sine of a number. Sin(3)=
0.1411200080598
cos() Return the cosine of a number. Cos(3)=
-0.989992496600
Function Description Example
tan() Return the tangent of a number. Tan(10)=
0.64836082745
Base_convert() Convert any base number to any base Base_convert($n1,
number. For example, you can convert 10,2)=1010
hexadecimal number to binary, hexadecimal
to octal, binary to octal, octal to
hexadecimal, binary to decimal etc.
Pi() Returns the value of pi. 3.14159265

Exp() Returns exponent of e Exp(0)=1

Fmod() Returns the floating point remainder. Fmod(5,2)=1


Function Description Example

Hexdec() Convert a hexadecimal to a decimal Hexdec(a)=10


number.
Log() To find the natural logarithm of a Log(2)=
number 0.69314718055
Max() To find the highest value. Max(20,30,5,10)=
30
Min() To find the lowest value. Min(20,30,5,10)=
5
Octdec() To convert an octal number to a Octdec(36)=30
decimal number.
Pow() It raises the first number to the power Pow(3,2)=9
of the second number.
PHP Date Functions
PHP date function is an in-built function that works with date data types. The PHP date function is
used to format a date or time into a human readable format.
Syntax: date(format, timestamp)

<?php
echo "Today's date is :"; Output :
$today = date("d/m/Y"); Today's date is :11/11/2019
echo $today;
?>
Format: Specifies the format of the outputted date string. The following characters can be used to
display various formatted output :

Format Description
d The day of the month (from 01 to 31)
D A textual representation of a day (three letters)
j The day of the month without leading zeros (1 to 31)
l A full textual representation of a day
(lowercase 'L')
N numeric representation of a day (1 for Monday, 7 for Sunday)
S The English ordinal suffix for the day of the month (2 characters st, nd, rd or
th. Works well with j)
z The day of the year (from 0 through 365)
w A numeric representation of the day (0 for Sunday, 6 for Saturday)
W week number of year (weeks starting on Monday)
Format Description
F A full textual representation of a month (January through December)
m A numeric representation of a month (from 01 to 12)
M A short textual representation of a month (three letters)
t The number of days in the given month
Y A four digit representation of a year
y A two digit representation of a year
a Lowercase am or pm
A Uppercase AM or PM
g 12-hour format of an hour (1 to 12)
G 24-hour format of an hour (0 to 23)
h 12-hour format of an hour (01 to 12)
H 24-hour format of an hour (00 to 23)
Time():The time() function is used to get the current time as a Unix timestamp (the number of
seconds since the beginning of the Unix epoch: January 1 1970 00:00:00 GMT).

<?php
$timestamp = time();
echo($timestamp); Output :
echo "<br/>"; 1573445225
echo(date("F d, Y h:i:s A", November 11, 2019 05:07:05 AM
$timestamp));
?>
Basic Graphics Concepts
Creating an Image”

To create an image in memory to work with, you start with the GD2 imagecreate () function.

Syntax :
imagecreate(x_size, y_size);

The x_size and y_size parameters are in pixels.

Here’s how to create a first image.


$img_height = 100;
$img_width=300;
$img=imagecreate($img_height, $img_width);
To set colors to be used in the image, you use the imagecolorallocate( ) function .

Syntax :
imagecolorallocate(image, red, green, blue);

You pass this function the image you’re working with, as well as the red, green, and blue components as 0- 255
value. For example, if you want solid red, you’d pass imagecolorallocate a red value of 255, and blue and green
values of 0.

$back_color= imagecolorallocate ($image, 200, 0, 0);


Images with text
The imagestring() function is an inbuilt function in PHP which is used to draw the string horizontally. This
function draws the string at given position.

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

•$image: The imagecreate or imagecreatetruecolor() function is used to create an image in a given size.
•$font: This parameter is used to set the font size. Inbuilt font in latin2 encoding can be 1, 2, 3, 4, 5 or
other font identifiers registered with imageloadfont() function.
•$x: This parameter is used to hold the x-coordinate of the upper left corner.
•$y: This parameter is used to hold the y-coordinate of the upper left corner.
•$string: This parameter is used to hold the string to be written.
•$color: This parameter is used to hold the color of image.
<?php
header ("Content-type: image/png");
$handle = ImageCreate (130, 50);
$bg_color = ImageColorAllocate ($handle, 240, 240,140);
$txt_color = ImageColorAllocate ($handle, 0, 0, 0);
ImageString ($handle, 5, 5, 18, "MSBTE.org.in", $txt_color);
imagepng ($handle);
?>
Displaying images in HTML pages

<html>
<head>
<tilte>
Embedding created images in HTML pages
</title>
</head>
<body>
<h2> Embedding created images in HTML pages </h2>
This is a blank image created on the server:
<br>
<img src="img2.php">
</body>
</html>
Scaling Images

• There are two ways to change the size of an image. The ImageCopyResized( ) function is available
in all versions of GD. The ImageCopyResampled( ) function is new in GD 2.x and features pixel
interpolation to give smooth edges and clarity to resized images (it is, however, slower than
ImageCopyResized( )).

• imagecopyresampled() 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.

• In other words, imagecopyresampled() will take a rectangular area from src_image of width
src_w and height src_h at position (src_x,src_y) and place it in a rectangular area of dst_image of
width dst_w and height dst_h at position (dst_x,dst_y).
Syntax:

imagecopyresampled ( resource$dst_image , resource$src_image , int$dst_x , int$dst_y , int$src_x ,


int$src_y , int$dst_w , int$dst_h , int$src_w , int$src_h )

dst_image : Destination image link resource.


src_image : Source image link resource.
dst_x: x-coordinate of destination point.
dst_y: y-coordinate of destination point.
src_x: x-coordinate of source point.
src_y: y-coordinate of source point.
dst_w: Destination width.
dst_h: Destination height.
src_w: Source width.
src_h: Source height.
<?php
$src = ImageCreateFromJPEG('academics.jpg');
$width = ImageSx($src);
$height = ImageSy($src);
$x = $width/2;
$y = $height/2;
$dst = ImageCreateTrueColor($x,$y);
ImageCopyResampled($dst,$src,0,0,0,0,$x,$y,
$width,$height);
header('Content-Type: image/png');
ImagePNG($dst);
?>

77
• imagecopyresized() copies a rectangular portion of one image to another image. dst_image is the
destination image, src_image is the source image identifier.
• In other words, imagecopyresized() will take a rectangular area from src_image of width src_w and
height src_h at position (src_x,src_y) and place it in a rectangular area of dst_image of width dst_w
and height dst_h at position (dst_x,dst_y).
Syntax :
imagecopyresized ( resource$dst_image , resource$src_image , int$dst_x , int$dst_y , int$src_x ,
int$src_y , int$dst_w , int$dst_h , int$src_w , int$src_h )

78
<?php
$src = ImageCreateFromJPEG('php.jpg');
$width = ImageSx($src);
$height = ImageSy($src);
$x = $width/2;
$y = $height/2;
$dst = ImageCreateTrueColor($x,$y);
imagecopyresized($dst,$src,0,0,0,0,$x,$y,$width,$height);
header('Content-Type: image/png');
ImagePNG($dst);

?>

79
Creation of PDF Document
• FPDF is a PHP class which allows to generate PDF files with PHP code. F from FPDF
stands for Free: It is free to use and it does not require any API keys. you may use it for
any kind of usage and modify it to user needs.
• Advantages of FPDF :
1. Choice of measure unit, page format and margins
2. Allow to set Page header and footer management
3. It provides automatic line break, Page break and text justification
4. It supports Images in various formats (JPEG, PNG and GIF)
5. It allows to setup Colors, Links, TrueType, Type1 and encoding support
6. It allows Page compression

• Link to Download latest version of FPDF class: http://www.fpdf.org/en/download.php


80
<?php
require('fpdf.php');
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(60,10,'Hello PHP
World!',1,1,'C');
$pdf->Output();
?>

81
Thank You

82
83

You might also like