1. Web Based Development Using PHP
(WBP)
Chapter 2
Arrays, Functions and Graphics
Mr. Shaikh M.R
2. What is an Array :-
Array in PHP is a type of data structure that allows to store multiple elements of
similar type data under 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 value
to keys.
The arrays are helpful to create a list of elements of similar types, which can be
accessed using their index or key.
An array is created using an array() function in PHP.
Types of Array
1. Indexed or Numeric Arrays
2. Associative Array
3. Multidimensional Array
3. 1. Indexed or Numeric Arrays :-
An array with a numeric index where values are stored linearly.
Numeric arrays use number as access keys.
An access keys is a reference to a memory slot in an array variable.
There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0), like this:
$cars = array ("Volvo", "BMW", "Toyota");
or the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
4. 2. Associative Arrays :-
This type of array is similar to 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 arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
5. 3. Multidimensional Array:-
These arrays can contain other nested array
An array which contain single or multiple arrays within it and can be accessed via
multiple indices.
We can create one dimensional and two dimensional array using multidimensional
array.
The advantage of multidimensional arrays is that they allows us to group related data
together.
We can store the data from the table above in a two-dimensional array, like this:
<html>
<body>
<?php
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
</body>
</html>
6. Extracting Data From Array:-
You can use the extract() function to extract data from arrays and store it in
variables.
Example :-
<html>
<body bgcolor="Yellow" Text="Red">
<h1>Extracting Array in PHP</h1>
<?php
$a = "Original";
$my_array = array("c" => "Cat","d" => "Dog", "h" => "Horse");
extract($my_array);
echo "$c = $c; $d = $d; $h = $h";
?>
</body>
</html>
In Fact List() function is also used to extract variables from an array
<?php
$course[0]=“Computer Engineering”;
$course[1]=“Information Technology”;
$course[2]=“Electronics & Telecommunication”;
List($one,$two)=$course;
Echo $one,”<BR>”;
Echo $two;
?>
7. Compact () Function :-
This function is opposite of extract () function. it returns an array with all the
variables added to it. Each parameter can be either a string containing the name of the
variable ,or an array of variable names. The compact () function creates associative array
whose key value are the variable name and whose values are the variable values.
Example :-
<?php
$firstname = "Virat";
$lastname = "Kohli";
$age = "35";
$result = compact("firstname", "lastname", "age");
print_r($result);
?>
Print_r() Function:-
The print_r() function prints the information about a variable in a more human-
readable way.
Syntax Example
print_r (variable, return); <?php
$a = array("red", "green", "blue");
print_r($a);
echo "<br>";
$b = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
print_r($b);
?>
8. Implode () Function :-
The implode () function 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 array elements, we can use the implode () function to join them all to form
one string.
Syntax:- implode (separator, array)
Example :-
<?php
$arr = array('Hello',‘Students!',‘Welcome',’To’,’PHP’,‘World!');
echo implode(" ",$arr);
?>
OUTPUT :-
Hello Students! Welcome To PHP World!
9. Explode () Function :-
The explode () function breaks the 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 string based on a string delimiter, i.e it splits the string
wherever the delimiter character occurs.
Syntax:- explode (separator,string,limit)
Example :-
<?php
$str = "Hello Students! Welcome To PHP World!";
print_r (explode(" ",$str));
?>
OUTPUT :-
Array ( [0] => Hello [1] => Students! [2] => Welcome [3] => To [4] => PHP [5] => World! )
10. Array_flip () Function :-
The array_flip() function flips/exchanges all keys with their associated values in an
array.
This is built-in function of PHP array_flip() is used to exchange elements in an array.
i.e. exchange all keys with their associated values in an array and vice-versa.
Syntax :-
array_flip(array)
Example :-
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$result= array_flip($a1);
print_r ($result);
?>
OUTPUT:-
Array ( [red] => a [green] => b [blue] => c [yellow] => d )
11. 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 accept a variable name as parameter and destroy or
unset that variable.
Syntax:-
void unset ($var,…);
Example :-
<?php
$course =array(“CO”,”IF”,”EJ”,”ME”,”CE”);
Echo”<h2>Before Deletion:<>/h2><br>”;
Echo”$course[0]<br>”;
Echo”$course[1]<br>”;
Echo”$course[2]<br>”;
Echo”$course[3]<br>”;
Echo”$course[4]<br>”;
Unset($course[3]); // deleting 3rd element
Echo”<h2>After Deletion:</h2><br>”;
Print_r ($course);
Echo”<h2> Delete Entire Array Element</h2><br>”;
Unset($course); //Delete All elements from an array
?>
12. 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 array in ascending order.
2. rsort ():- Sorts array 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.
15. PHPArray Functions :-
1. Array_diff ():- It Compares the values of two array’s and return the differences.
Syntax :- array_diff(array1,array2,array3….)
Example :- $a1=array(‘PHP,’C’,’Java’,’Perl’);
$a2=array(‘PHP’,’ASP’,’Java’,’Python’);
array_diff ($a1,$a2);
Output:- Array([1]=>c [3]=>Perl)
2. Array_intersect():- It Compares the values of two arrays, and return the matches.
Syntax :- array_intersect (array1,array2,array3…..)
Example :- $a1=array(‘PHP,’C’,’Java’,’Perl’);
$a2=array(‘PHP’,’ASP’,’Java’,’Python’);
array_intersect ($a1,$a2);
Output:- Array ([0]=>PHP [2]=>Java)
16. 3.Array_combine ():- It creates an array by using the elements from one “keys”
array and one “values” array.
Syntax :- array_combine (keys,values)
Example :- $a1=array(“PHP”,”Java”,”Perl”);
$a2=array(“10”,”20”,”30”);
$ac=array_combine($a1,$a2);
Print_r ($ac);
Output:- Array ([PHP]=>10 [Java]=>20 [Perl]=>30)
4. Array_unique ():- It removes duplicate values from an array.
Syntax :- array_unique (array, sorttype)
Example :- $a1=array(“10”,”20”,”30”,”20”);
$au=array_unique($a1);
Print_r ($au);
Output :- Array([0]=>10 [1]=>20 [2]=>30)
17. 5. Array_count_values ():- It is used to count all the values of an array.
Syntax :- array_count_values(array)
Example :- $a1=array(“10”,”20”,”30”,”20”);
Print_r (array_count_values($a1));
Output :- Array ( [10] => 1 [20] => 2 [30] => 1 )
6. Array_Chunks :-
It Split an array into chunks of two and preserve the original key.
Syntax : - array_chunk (array,size,preserve_key)
Example :- $a1=array(‘PHP’,’C’,’Java’,’Perl’);
$ac=array_chunk($a1,2);
print_r ($ac);
Output :-
Array([0]=>array([0]=>PHP [1]=>C)[1]=>Array([0]=>Java [1]=>Perl))
18. 6. Array_Merge ():- It Merge Two array into one array.
Syntax :- array_merge (array1,array2,array3…)
Example :- $a1=array(“10”,”20”);
$a2=array(“30”,”40”);
$am= array_merge($a1,$a2);
print_r ($am);
Output:- Array([0]=>10 [1]=>20 [2]=>30 [3]=>40)
7. Array_pop ():- It Delete the last element of an array.
Synatx: - array_pop (array)
Example :- $a1=array(“10”,”20”,”30”);
array_pop ($a1);
Output :- Array ([0]=>10 [1]=>20)
19. 8. Array_product () :- It Calculate and return the product of an array.
Syntax :- array_product (array);
Example :- $a1=array(10, 20);
$ap=array_product($a1);
echo $ap;
Output :- 200
9. Array_push ():- It insert one or more elements to the end of an array.
Syntax:- array_push (array,value1,value2….);
Example :- $a1= array(10,20);
$ap=array_push ($a1,”PHP”,”Python”);
Print_r ($ap);
Output
Array([0]=>10 [1]=>20 [2]=>PHP [3]=>Python
20. 10. Array_reverse ():- It returns an array in the reverse order.
Syntax :- array_reverse(array, preserve);
Example :- $a1= array(“a”=>”PHP”,”b”=>”Java”,”c”=>”perl”);
$ar =array_reverse($a1);
print_r ($ar);
Output :- Array([c]=>perl [b]=> Java [a]=>PHP)
11. Array_sum ():- It returns the sum of all the values in the array.
Syntax :- array_sum (array)
Example :- $a1=array(10,20,30);
$as= array_sum($a1);
echo $as;
Output :- 60
21. 12. Count () :- It returns the number of elements in an array.
Syntax :- count(array)
Example :- $a1=array(10,20,30);
$ac=count($a1);
echo $ac;
Output :- 3
13. Array_search :- It Search an array for a value and return the key.
Syntax :- array_search (value, array);
Example :- $a1=array(“a”=>”PHP”, ”b”=>”Java”,”c”=>”Perl”);
$as= array_search (“Java”,$a1);
echo $as;
Output :- b
22. PHP String Functions :-
1. Str_word_count () :- It count the number of words in a string.
Syntax :- str_word_count (string)
Example :- <?php
echo str_word_count (“Welcome to PHP World!”);
?>
Output:- 4
2. Strlen ():- It returns the length of string
Syntax:- strlen (string)
Example :- <?php
echo strlen (“Welcome to PHP World!”);
?>
Output :- 21
23. 3. Strrev () :- It reverse a string.
Syntax :- strrev (string);
Example :- <?php
echo strrev (“Computer Technology”);
?>
Output:- ygolonhceT retupmoC
4. str_replace():- It replace some character in a string.
Syntax :- str_replace (string to be replaced, text,string)
Example :- <?php
echo str_replace(“Clock”,”Click”,”Click”,”Clock”);
?>
Output :- Click and Clock
24. 5. Ucwords ():- Convert the first character of each word to uppercase.
Syntax :- Ucwords (string)
Example :- <?php
Echo ucwords (“welcome to php word’);
?>
Output:- Welcome To Php Word
6. Strtoupper ():- It Convert a string to Uppercase letters.
Syntax :- strtoupper (string)
Example:- <?php
echo strtoupper (“Computer Technology”);
?>
Output :- COMPUTER TECHNOLOGY
25. 7. Strtolower ():- It converts a string to lowercase letters.
Syntax :- strtolower (string)
Example : - <?php
Echo strtolower (“COMPUTER TECHNOLOGY”);
?>
Output :- computer technology
8. str_repeat () :- It repeat a string with a specific number of times.
Syntax :- str_repeat (string, repeat)
Example :- <?php
Echo str_repeat (“*”,10);
?>
Output :- **********
26. 9. strcmp():- It compares two string (case-sensitive) .
if this function returns 0 the two strings are equal.
if this function returns any negative or positive numbers, the two strings
are not equal.
Syntax :- strcmp (string1, string2)
Example :- <?php
echo strcmp (“Hello Php”, “Hello Php”);
?>
Output :- 0
Example :- <?php
echo strcmp (“hello php”, “Hello Php”);
?>
Output :- -20
27. 10. substr():- It is used to display or extract a string from a particular position.
Syntax :- substr ( string, start, length)
Example :- <?php
echo substr (“Welcome to PHP”,11)”<br>”
echo substr (“Welcome to PHP”,0,7)”<br>”
?>
Output :- PHP
Welcome
11. str_split ():- It is used to convert a string into an array.
Syntax :- str_split (string, length)
Example :- $str=“PHP”
$ss= str_split($str);
print_r ($ss);
Output :- Array([0]=>P[1]=>H[2]=>P)
28. 12. str_shuffle () :- To randomly shuffle all the character of a string.
Syntax :- str_shuffle (string)
Example :-<?
$str=“PHP”
$ss=str_shuffle($str);
echo $ss;
?>
Output :- PPH
13.Trim () :- It removes the white spaces and predefined character from a both the
side of a string.
Syntax :- trim (string,charlist)
Example :- $str=“ Welcome ”;
trim ($str);
Output :- Welcome
Types of Trim :- 1. Rtrim () 2. Ltrim()
29. 14.Chop() :- It removes the white spaces or other predefined characters from the
right end of a string.
Syntax:- chop (String, charlist)
Example :- $str=“Hello World”
chop($str, ”World”)
Output :- Hello
15.Chunk_split ():- It splits a string into smaller parts or chunks .
Syntax :- chunk_split (string,length,end)
Example :- $str=“Hello World”
chunk_split($str, 6,”!!!”)
Output :- Hello!!!World!!!
30. Math Functions in PHP :-
1. Abs ():- It returns absolute value of given number.
Syntax :- number abs (mixed $ number)
Example :- abs (-7) = 7
2. Ceil ():- It rounds fraction up.
Syntax :- float ceil
(float $value)
Example :- ceil (3.3) = 4
ceil (-4.6)= - 4
3. floor():- It rounds fraction down.
Syntax :- float floor
(float $value)
Example :- floor (3.3)=3
floor(-4.6)=-5
31. 4. Sqrt ():- It returns square root of given argument.
Syntax :- float sqrt
(float $arg)
Example :- sqrt (16) = 4
5. Decbin ():- It converts decimal number into binary. It returns binary number
as a string.
Syntax :- string decbin
(int $number)
Example :- decbin (2) = 10
decbin (10)= 1010
6. Dechex ():- It converts decimal number into hexadecimal. it returns
hexadecimal representation of given number as a string.
Syntax :- string dechex
(int $number)
Example :- dechex (10) = a
dechex (22)=16
32. 7. Decoct () :- It converts decimal number into octal.it returns octal
representation of given number as a string.
Syntax :- string decoct
(int $number)
Example :- decoct(10) = 12
decoct(22) = 26
8. Bindec ():- It converts binary number into decimal.
Syntax :- number bindec
(string $binary_string)
Example :- bindec (10) = 2
bindec (1010)=10
33. 9. sin():- It returns the sin of a number
Syntax :- float sin (float $arg)
Example :- sin(3) = 0.1411200080598
10. Cos () :- It returns cosine of a number
Syntax :- float cos (float $arg)
Example :- cos (3)=0.989992496600
11. tan ():- It returns the tangent of a number
Syntax :- float tan (float $arg)
Example :- tan(10) = 0.64836082745
34. Function : - Functions are similar to other types of programming languages.
A Function is a piece of code which takes one or more input in the
form of parameter and does some processing and returns a value.
Syntax :- function function name ()
{
Code to be executed
}
35. Assignments :-
1. Write a PHP Program to Check whether number is even or odd using
function.
2. Calculate Sum of Digits using function
3. Calculate the factorial number using function.
36. PHP Date Functions :-
PHP date function is an in-built functions 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)
Example :- <?php
Echo “Todays date is :- ”;
$today = date(“d/m/Y”);
Echo $today;
?>
Output :- Todays date is :26/04/2021
37. 1. d :- It is used to display day of the month (from 01 to 31).
2. D:- It is used to display a textual representation of a day (Three Letters).
3. j :- It is used to display day of the month without leading zeros (from 1 to 31).
4. l :- It is used to display a full textual representation of a day.
5. N :- It is used to display numeric representation of a day (1 for Monday and 7
for Sunday).
6. z :- It is used to display day of the year (from 0 to 365).
7. w:- It is used to display numeric representation of the day (0 for Sunday and 6
for Saturday).
8. W:- It is used to display week number of year (week starting on Monday ).
9. F :- It is used to display a full textual representation of a month (January
through December)
10. m:- It is used to display representation of a month (01 to 12)
11. M :- It is used to display a short textual representation of a month (three
letters).
12. t:- It is used to display the number of days in the given month.
13. Y:- It is used to display four digit representation of a year.
14. y:- It is used to display two digit representation of year.
38. 15. a:- It is used to display Lowercase am and pm.
16. A:- It is used to display Uppercase AM and PM.
17. g:- It is used to display 12-hour format of an hour (1 to 12).
18. G:- It is used to display 24 hours format an hour (0-23)
19. h:- It is used to display 12 hour format an hour (01 to 12)
20. H:- It is used to display 24 hour format an hour (00-23).
39. Basic Graphic Concept in PHP :-
The web is more than just text. images appear in the form of logos, buttons,
photographs, charts, advertisements and icons. PHP support graphics creation with
the GD and lmlib2 extensions.
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 pixel.
Example :- $img_height=100;
$ img_width=300;
$img=imagecreate($img_height,$img_width);
Set color image :- imagecolorallocate() function is used to set image color.
Syntax:- imagecolorallocate($image,red,green,blue);
Example :- $back_color = imagecolorallocate ($image,200,0,0),
40. Images with text :- The imagestring() function is an inbuilt function in PHP
which is used to draw the string horzontally. This function draws the string at
given position.
Syntax :- bool imagestring ($image, $font, $x, $y, $string, $color);
1. $image :- The imagecreate () or imagecreatetruecolor() function is used to
create an image in a given size.
2. $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 identifier registered with
imageloadfont() function.
3. $x:- This parameter is used to hold the x-coordinates of the upper left corner.
4. $y:- This parameter is used to hold the y-coordinates of the upper right corner.
5. $string :- This parameter is used to hold the string to be written.
6. $color:- This parameter is used to hold the color of image.
41. Here some of the image creating function for various image format
1. Imagegif ():-Output a GIF image to browser or file.
2. Imagejpeg ():-Output a JPEG image to browser or file.
3. Imagewbmp ():-Output a WBMP image to browser or file.
4. Imagepng ():- Output a PNG image to browser or file.
5. Imagedestroy ():- This function used to destroy the object created by image
function
42. Image Scaling :- there are two ways to change the size of image .
imagecopyResized () :- it is available in all versions of GD.
imagecopyresampled () :- it is available in GD 2.x.
imagecopyresampled () :- it is used to copies rectangular portion of one image
to another image, smoothly interpolating pixel values so that in prrticular
reducing the size of image still retains a great deal of clarity.
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);
43. Parameters :-
dst_image :- Destination Image Link Source
src_image:- Source image link resource
dst_x:- x-coordinates of destination point
dst_y:- y-coordinates of destination point
src_x:- x-coordinates of source point
src_y:- y-coordinates of source point
dst_width:- Destination Width
dst_h:- Destination Height
src_w:- Source Width
src_h:-Source height
44. Imagecopyresized():- It is used to copies a rectangular portion of one image to
another image. dst_image is the destination image, src_image is source image
identifier.
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);