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

Chapter-2(WBP)

Uploaded by

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

Chapter-2(WBP)

Uploaded by

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

Mrs.

Poonam Amit Kamble Web based Application Development with PHP(22619)

2.1  Creating and Manipulating Array


 Types of Arrays
 Indexed Array
 Associative Array
 Multidimensional Array
2.2  Extracting Data from Arrays
 Implode
 Explode
 Array flip
2.3 Traversing Arrays
2.4 Functions and its Types :
 User Defined
 Variable Function
 Anonymous Function
2.5 Operations on String and String Functions :
 str_word_count()
 strlen()
 strrev()
 strpos()
 str_replace()
 ucwords()
 strtoupper()
 strtolower()
 strcmp()
2.6  Basic Graphics Concepts
 Creating Images
 Images with text
 Scaling Images
 Creation of PDF document

Unit II
Arrays, Functions and Graphics Page 1
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

2.1 Array
Definition:
An array is an ordered collection of elements. The elements are of same data type or
different data type. Each element has a value, and is identified by a key. Each array
has its own unique keys. The keys can be either integer numbers or strings.

(1) Creating and Manipulating Array:


There are following ways of creating array:
1) Using array() function
2) Using array identifier

1) Using array() function:


 In PHP, the array() function is used to create an array:
array( );
 Syntax:
$ArrayName = array(value1,value2….valueN);

 In Numeric array each elements are assigned a numeric key value starting
from 0 for first elements and so on.

 Example:
<?php
$name=array(―Archana‖, ―Sanket‖, ―Helisha‖);
print_r($name);
?>
 Output:
Array([0] => Archana [1] => Sanket [2]=>Helisha)

2) Using array identifier


 In PHP, we can also create an array using array identifier.

 Syntax:
$ArrayName [ ] = ―value‖;

 Example:
<?php
$name[ ] = ―Soham‖;
$name[ ] = ―Helisha‖;

Unit II
Arrays, Functions and Graphics Page 2
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

print_r($name);
?>

 Output:
Array([0] =>Arpan [1] =>Soham [2]=>Helisha)

Defining Starting index:


 By default starting index of an array is 0. It is incremented by 1 for each
successive elements of an array. But it is also possible to define start index of
an array.

 Example:
<?php
$name = array(19=> ―Arpan‖, ―Charmi‖, ―Reshma‖);
print_r($name);
?>

 Output:
Array ([19]=> Arpan [20]=>Charmi [21]=>Reshma)

Adding More Elements To Array:


 Once an array id created we can add more elements to an array using array
identifier.

 Example:
<?php
$name=array(―Arpan‖, ―Soham‖, ―Helisha‖);
print_r($name);
echo ―<br>‖;
$name[ ] = ―Sagar‖;
print_r($name);
?>

 Output:
Array([0] =>Arpan [1] =>Soham [2]=>Helisha)
Array([0] =>Arpan [1] =>Soham [2]=>Helisha [3]=>Sagar)

(2) Types of Arrays


Unit II
Arrays, Functions and Graphics Page 3
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

There are three different kinds of arrays and each array value is accessed using an
array index.

1. Indexed Array
These arrays can store numbers, strings and any object but their index will be pre
presented by numbers. By default array index starts from zero.

Example
Following is the example showing how to create and access numeric arrays.
Here we have used array()function to create array. This function is explained in
function reference.

<html>
<body>
<?php
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
echo "Value is $value <br />";
}
echo"<pre>";
Print_r($numbers);
echo"</pre>";?>
</body>
</html>

Output:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5

Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)

2. Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality

Unit II
Arrays, Functions and Graphics Page 4
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

but they are different in terms of their index. Associative array will have their
index as string so that you can establish a strong association between key and
values.

Example

<html>
<body>
<?php
$salaries = array(
"mohammad" => 2000, "Dinesh" => 1000, "Surabhi" => 500
);
echo "Salary of Arjun is ". $salaries['Arjun'] . "<br />";
echo "Salary of Dinesh is ". $salaries['Dinesh']. "<br />";
echo "Salary of Surabhi is ". $salaries['Surabhi']. "<br />";
echo "<pre>";
print_r($salaries);
echo "</pre>";
?>
</body>
</html>

Output
Salary of Arjun is 2000
Salary of Dinesh is 1000
Salary of Surabhi is 500
Array
(
[Arjun] => 2000
[Dinesh] => 1000
[Surabhi] => 500
)

3. Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array.
And each element in the sub-array can be an array, and soon. Values in the multi-
dimensional array are accessed using multiple indexes.

Example
In this example we create a two dimensional array to store marks of three students
in three subjects:
<html>
<body>
<?php
$marks = array(

Unit II
Arrays, Functions and Graphics Page 5
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

"Arjun" => array


(
"physics" => 35, "maths" => 30, "chemistry" => 39
),
"Dinesh" => array
(
"physics" => 30, "maths" => 32, "chemistry" => 29
),
"Surabhi" => array
(
"physics" => 31, "maths" => 22, "chemistry" => 39
)
);
/* Accessing multi-dimensional array values */
echo "Marks for Arjun in physics : " ;
echo $marks['Arjun']['physics'] . "<br />";
echo "Marks for Dinesh in maths : ";
echo $marks['Dinesh']['maths'] . "<br />";
echo "Marks for Surabhi in chemistry : " ;
echo $marks['Surabhi']['chemistry'] . "<br />";
echo "<pre>";
print_r($marks);
echo "</pre>";
?>
</body>
</html>
0
Output:
Marks for Arjun in physics : 35
Marks for Dinesh in maths : 32
Marks for Surabhi in chemistry : 39
Array
(
[Arjun] => Array
(
[physics] => 35
[maths] => 30
[chemistry] => 39
)

[Dinesh] => Array


(
[physics] => 30
[maths] => 32
[chemistry] => 29
)
Unit II
Arrays, Functions and Graphics Page 6
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

[Surabhi] => Array


(
[physics] => 31
[maths] => 22
[chemistry] => 39
)

2.2 In-Built Functions of Array

1) sizeof($arr)
 This function returns the number of elements in an array. Use this function to
find out how many elements an array contains; this information is most
commonly used to initialize a loop counter when processing the array.
 Example:
<?php
$data = array("red", "green", "blue");
echo "Array has " . sizeof($data) . " elements";
?>
 Output
Array has 3 elements

2) array_values($arr)
 This function accepts a PHP array and returns a new array containing only its
values (not its keys). Its counterpart is the array_keys() function. Use this
function to retrieve all the values from an associative array.
 Example
<?php
$data = array("hero" => "Holmes", "villain" => "Moriarty");
print_r(array_values($data));
?>
 Output
Array
(
[0] => Holmes
[1] => Moriarty
)

3) array_keys($arr)
 This function accepts a PHP array and returns a new array containing only its
keys (not its values). Its counterpart is the array_values() function. Use this
function to retrieve all the keys from an associative array.
Unit II
Arrays, Functions and Graphics Page 7
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 Example
<?php
$data = array("hero" => "Holmes", "villain" => "Moriarty");
print_r(array_keys($data));
?>
 Output:
Array
(
[0] => hero
[1] => villain
)

array_pop($arr)
4)
 This function removes an element from the end of an array.
 Example
<?php
$data = array("Donald", "Jim", "Tom");
array_pop($data);
print_r($data);
?>
 Output
Array
(
[0] => Donald
[1] => Jim
)

5) array_push($arr, $val)
 This function adds an element to the end of an array.
 Example
<?php
$data = array("Donald", "Jim", "Tom");
array_push($data, "Harry");
print_r($data);
?>
 Output
Array
(
[0] => Donald
[1] => Jim
[2] => Tom
[3] => Harry
)

Unit II
Arrays, Functions and Graphics Page 8
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

6) array_shift($arr)
 This function removes an element from the beginning of an array.
 Example
<?php
$data = array("Donald", "Jim", "Tom");
array_shift($data);
print_r($data);
?>
 Output
Array
(
[0] => Jim
[1] => Tom
)
7) array_unshift($arr, $val)
 This function adds an element to the beginning of an array.
 Example
<?php
$data = array("Donald", "Jim", "Tom");
array_unshift($data, "Sarah");
print_r($data);
?>
 Output:
Array(
[0] => Sarah
[1] => Donald
[2] => Jim
[3] => Tom
)

array_flip($arr)
8)
 The function exchanges the keys and values of a PHP associative array. Use this
function if you have a tabular (rows and columns) structure in an array, and you
want to interchange the rows and columns.
 Example
<?php
$data = array("a" => "apple", "b" => "ball");
print_r(array_flip($data));
?>
 Output
Array
(
[apple] => a
[ball] => b )
Unit II
Arrays, Functions and Graphics Page 9
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

9) array_reverse($arr)
 The function reverses the order of elements in an array. Use this function to re-
order a sorted list of values in reverse for easier processing—for example, when
you‘re trying to begin with the minimum or maximum of a set of ordered values.
 Example
<?php
$data = array(10, 20, 25, 60);
print_r(array_reverse($data));
?>
 Output
Array
(
[0] => 60
[1] => 25
[2] => 20
[3] => 10
)

array_merge($arr)
10)  This function merges two or more arrays to create a single composite array. Key
collisions are resolved in favor of the latest entry. Use this function when you
need to combine data from two or more arrays into a single structure. For
example, records from two different SQL queries.
 Example
<?php
$data1 = array("cat", "goat");
$data2 = array("dog", "cow");
print_r(array_merge($data1, $data2));
?>
 Output
Array
(
[0] => cat
[1] => goat
[2] => dog
[3] => cow )

array_rand($arr)
11)  This function selects one or more random elements from an array. Use this
function when you need to randomly select from a collection of discrete values.
For example, picking a random color from a list.
 Example
<?php
$data = array("white", "black", "red");
echo "Today's color is " . $data[array_rand($data)];
Unit II
Arrays, Functions and Graphics Page 10
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

?>
 Output
Today‘s color is red

array_search($search, $arr)
12)  This function searches the values in an array for a match to the search term, and
returns the corresponding key if found. If more than one match exists, the key of
the first matching value is returned. Use this function to scan a set of index-value
pairs for matches, and return the matching index.
 Ex-
<?php
$data = array("blue" => "#0000cc", "black" => "#000000", "green" =>
"#00ff00");
echo "Found " . array_search("#0000cc", $data);
?>
 Output
Found blue

array_slice($arr, $offset, $length)


13)  This function is useful to extract a subset of the elements of an array, as another
array. Extracting begins from array offset $offset and continues until the array
slice is $length elements long. Use this function to break a larger array into
smaller ones—for example, when segmenting an array by size (―chunking‖) or
type of data.
 Example
<?php
$data = array("vanilla", "strawberry", "mango", "peaches");
print_r(array_slice($data, 1, 2));
?>
 Output
Array
(
[0] => strawberry
[1] => mango
)

array_unique($data)
14)  This function strips an array of duplicate values. Use this function when you
need to remove non-unique elements from an array. For example, when creating
an array to hold values for a table‘s primary key.
 Example
<?php
$data = array(1,1,4,6,7,4);
print_r(array_unique($data));
Unit II
Arrays, Functions and Graphics Page 11
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

?>
 Output
Array
(
[0] => 1
[3] => 6
[4] => 7
[5] => 4
)

array_change_key_case()
15)  PHP array_change_key_case() function changes the case of all key of an array. It
changes case of key only.
 Example
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
print_r(array_change_key_case($salary,CASE_UPPER));
?>
 Output:
Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] => 200000 )
 Example
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
print_r(array_change_key_case($salary,CASE_LOWER));
?>
 Output:
Array ( [sonoo] => 550000 [vimal] => 250000 [ratan] => 200000 )

array_chunk()
16)  PHP array_chunk() function splits array into chunks. By using array_chunk()
method, you can divide array into many parts.
 Example
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
print_r(array_chunk($salary,2));
?>
 Output:
Array (
[0] => Array ( [0] => 550000 [1] => 250000 )
[1] => Array ( [0] => 200000 )
)

array_intersect()
Unit II
Arrays, Functions and Graphics Page 12
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

17)  PHP array_intersect() function returns the intersection of two array. In other
words, it returns the matching elements of two array.
 Example
<?php
$name1=array("sonoo","john","vivek","smith");
$name2=array("umesh","sonoo","kartik","smith");
$name3=array_intersect($name1,$name2);
foreach( $name3 as $n )
{
echo "$n<br />";
}
?>
 Output:
sonoo
smith

implode()
18)  The implode() is a built-in function in PHP and is used to join the elements of an
array. It works exactly same as that of join() function.
 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 :
implode(separator,array)

 Parameters: The implode() function accepts two parameter out of which one is
optional and one is mandatory.
1) 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).
2) array: The array whose value is to be joined to form a string.

 Return Type: The return type of implode() function is string. It will return the
joined string formed from the elements of array.

 Example:
<?php
// PHP Code to implement join function

$a= array('I','like','PHP');

Unit II
Arrays, Functions and Graphics Page 13
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

// Join without separator


print_r(implode($a));
echo"</br>";

// Join with separator


print_r(implode("-",$a));
echo"</br>";
print_r(implode(" ",$a));
?>

 Output:
IlikePHP
I-like-PHP
I like PHP

explode()
 explode() is a built in function in PHP used to split a string in different strings.
19) The explode() function splits a string based on a string delimiter, i.e. it splits the
string wherever the delimiter character occurs. This functions returns an array
containing the strings formed by splitting the original string.
 Syntax :
explode(separator, String, limit)

 Parameters: The explode function accepts three parameters of which two are
compulsory and one is optional.
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) String : The input string which is to be split in array.
3) limit : 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)
 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.
 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.
 Zero : If this parameter is Zero then the array returned will have only one
element i.e. the whole string.

 Return Type: The return type of explode() function is array of strings.


 Example:
<?php

Unit II
Arrays, Functions and Graphics Page 14
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

echo"<pre>";
$OriginalString = "Hello, How can we help you?";

echo"Without optional parameter limit";


print_r(explode(" ",$OriginalString));
print_r(explode(",",$OriginalString));
echo"</br>";

echo"with positive limit";


echo"</br>";
print_r(explode(" ",$OriginalString,3));
echo"</br>";
print_r(explode(",",$OriginalString,1));
echo"</br>";

echo"with negative limit";


echo"</br>";
print_r(explode(" ",$OriginalString,-1));
echo"</br>";
print_r(explode(" ",$OriginalString,-3));
echo"</pre>";
?>

 Output:
Without optional parameter limitArray
(
[0] => Hello,
[1] => How
[2] => can
[3] => we
[4] => help
[5] => you?
)
Array
(
[0] => Hello
[1] => How can we help you?
)

with positive limit


Array
(
[0] => Hello,
[1] => How
[2] => can we help you?
)
Unit II
Arrays, Functions and Graphics Page 15
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

Array
(
[0] => Hello, How can we help you?
)

with negative limit


Array
(
[0] => Hello,
[1] => How
[2] => can
[3] => we
[4] => help
)

Array
(
[0] => Hello,
[1] => How
[2] => can
)

Extract()
 The extract() Function is an inbuilt function in PHP. The extract() function does
array to variable conversion. That is it converts array keys into variable names
20) and array values into variable value.

 Syntax :
extract($array, $extract_rule, $prefix)

 Parameters: The extract() function accepts three parameters, out of which one is
compulsory and other two are optional.
1) $array: This parameter is required. This specifies the array to use.
2) $extract_rule: This parameter is optional. The extract() function checks for
invalid variable names and collisions with existing variable names. This
parameter specifies how invalid and colliding names will be treated. This
parameter can take the following values:
 EXTR_OVERWRITE: This rule tells that if there is a collision, overwrite
the existing variable.
 EXTR_SKIP: This rule tells that if there is a collision, don‘t overwrite the
existing variable.
 EXTR_PREFIX_SAME: This rule tells that if there is a collision then
prefix the variable name according to $prefix parameter.

Unit II
Arrays, Functions and Graphics Page 16
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 EXTR_PREFIX_ALL: This rule tells that prefix all variable names


according to $prefix parameter.
 $prefix: This parameter is optional. This parameter specifies the prefix. The
prefix is automatically separated from the array key by an underscore
character. Also this parameter is required only when the parameter
$extract_rule is set to EXTR_PREFIX_SAME, EXTR_PREFIX_ALL.
 Return Type: The return value of extract() function is an integer and it represents
the number of variables successfully extracted or imported from the array.

 Example:
<?php

$KR="KARNATAKA";
$state = array("AS"=>"ASSAM", "OR"=>"ORISSA", "KR"=>"KERALA");

echo $KR."</br>";
echo"</br>";

extract($state);

echo"after using extract() function without optional parameter</br>";


echo"$AS</br>$KR</br>$OR";
echo"</br>";
echo"</br>";
echo"With Extract Rules-Prefix same";
echo"</br>";
extract($state,EXTR_PREFIX_SAME,"key");
echo"$AS</br>$KR</br>$key_KR</br>$OR";
echo"</br>";
echo"</br>";
echo"With Extract Rules-Prefix all";
echo"</br>";
extract($state,EXTR_PREFIX_ALL,"key");
echo"$key_AS</br>$key_KR</br>$key_OR</br>$KR";
 ?>

 Output:
KARNATAKA

after using extract() function without optional parameter


ASSAM

Unit II
Arrays, Functions and Graphics Page 17
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

KERALA
ORISSA

With Extract Rules-Prefix same


ASSAM
KARNATAKA
KERALA
ORISSA

With Extract Rules-Prefix all


ASSAM
KERALA
ORISSA
KARNATAKA

Compact()
 The compact() function creates an array from variables and their values. Any
strings that does not match variable names will be skipped.

 Syntax :
21) compact(var1, var2...)

 Parameters: The compact() function accepts any no. of variables. Atleast one
variable is compulsory and others may be optional.
1) var1- Required. Can be a string with the variable name, or an array of
variables
2) var2,.. - Optional. Can be a string with the variable name, or an array of
variables. Multiple parameters are allowed.

 Return Type: Returns an array with all the variables added to it.

 Example:
<?php
echo"<pre>";
$firstname = "Akshay";
$lastname = "Deshapande";
$age = "41";

$name = array("firstname", "lastname");


$result = compact($name, "location", "age");

print_r($result);
echo"</pre>";
 ?>

Unit II
Arrays, Functions and Graphics Page 18
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 Output:
Array
(
[firstname] => Akshay
[lastname] => Deshapande
[age] => 41
)

Sorting Arrays in PHP


 Sorting is a process by which we can arrange the elements of a list in a specific
order i.e. ascending or descending order. We can say sorting is the process of
putting a list or a group of items in a specific order. Sorting may be alphabetical
or numerical.
 In PHP, sorting is a process of arranging the elements of an array in a specific
order i.e. ascending or descending order. Using sorting you can analyze a list in a
more effective way. You can sort an array by value, key or randomly. In the most
situations we need to sort an array by value.
 Some sorting functions are as follows:
1) sort()
2) asort()
3) rsort()
4) arsort()

1) sort()
Using the sort() function you can sort easily and simply. The example of the sort()
function is as follows:

Example:
<?php
$name=array ("Anuj","Sanjeev","Manish","Rahul");
echo "<b>Before sorting the values are:</b>".'<br>';
print_r($name).'<br>'.'<br>';
sort($name);
echo"<br/>";
echo"<br/>";
echo "<b>After sorting values become:</b>".'<br>';
print_r($name).'<br>';
?>

Output:
Before sorting the values are:
Array ( [0] => Anuj [1] => Sanjeev [2] => Manish [3] => Rahul )

After sorting values become:


Array ( [0] => Anuj [1] => Manish [2] => Rahul [3] => Sanjeev )

Unit II
Arrays, Functions and Graphics Page 19
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

2) asort() function
In the example above you saw that the elements of the array are arranged in
ascending (alphabetically) order. The asort() function sorts an array and also
maintains the index position.

Example
<?php
$name=array ("Anuj","Sanjeev","Manish","Rahul");
echo "<b>Before sorting the values are:</b>".'<br>';
print_r($name).'<br>'.'<br>';
asort($name);
echo"<br/>";
echo"<br/>";
echo "<b>After sorting values become:</b>".'<br>';
print_r($name).'<br>';
?>

Output
Before sorting the values are:
Array ( [0] => Anuj [1] => Sanjeev [2] => Manish [3] => Rahul )

After sorting values become:


Array ( [0] => Anuj [2] => Manish [3] => Rahul [1] => Sanjeev )

3) rsort() function
The rsort() function is used to sort an array in descending (alphabetic) order

Example:
<?php
$name=array ("Anuj","Sanjeev","Manish","Rahul");
echo "<b>Before sorting the values are:</b>".'<br>';
print_r($name).'<br>'.'<br>';
rsort($name);
echo"<br/>";
echo"<br/>";
echo "<b>After sorting values become:</b>".'<br>';
print_r($name).'<br>';
?>

Output:
Before sorting the values are:
Array ( [0] => Anuj [1] => Sanjeev [2] => Manish [3] => Rahul )

Unit II
Arrays, Functions and Graphics Page 20
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

After sorting values become:


Array ( [0] => Sanjeev [1] => Rahul [2] => Manish [3] => Anuj )

4) arsort() function
The arsort() function is a combination of asort() + rsort(). The arsort() function will
sort an array in reverse order and maintain index position.

Example
<?php
$name=array ("Anuj","Sanjeev","Manish","Rahul");
echo "<b>Before sorting the values are:</b>".'<br>';
print_r($name).'<br>'.'<br>';
arsort($name);
echo"<br/>";
echo"<br/>";
echo "<b>After sorting values become:</b>".'<br>';
print_r($name).'<br>';
?>

Output:
Before sorting the values are:
Array ( [0] => Anuj [1] => Sanjeev [2] => Manish [3] => Rahul )

After sorting values become:


Array ( [1] => Sanjeev [3] => Rahul [2] => Manish [0] => Anuj )

2.3 Traversing Arrays


Array traversing means accessing each element and perform some operations on it.
Array traversing can be done by using simple for and foreach loop. Instead we can
use inbuilt iteration functions

The Iterator Functions


Every PHP array keeps track of the current element you're working with; the pointer
to the current element is known as the iterator. PHP has functions to set, move, and
reset this iterator.

Example:
<?php
$colors = array("red", "green", "blue", "yellow");
echo"Array Elements are<br>"; Output :

foreach ($colors as $value) { Array Elements are


red
Unit II green
Arrays, Functions and Graphics blue Page 21
yellow
-----------------------------------
Using Iterator Function
-----------------------------------
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

echo "$value <br>";


}
echo"-----------------------------------<br>";
echo "Using Iterator Function<br>";
echo"-----------------------------------<br>";
echo"current=".current($colors)."<br>";
echo"-----------------------------------<br>";
echo"next=".next($colors)."<br>";
echo"-----------------------------------<br>";
echo"next=".next($colors)."<br>";
echo"-----------------------------------<br>";
echo"previous=".prev($colors)."<br>";
echo"-----------------------------------<br>";
echo"key=".key($colors)."<br>";
echo"-----------------------------------<br>";
echo"reset=".reset($colors)."<br>";
echo"-----------------------------------<br>";
echo"key=".key($colors)."<br>";
echo"-----------------------------------<br>";
echo"current=".current($colors)."<br>";
echo"-----------------------------------<br>";
echo"end=".end($colors)."<br>";
echo"-----------------------------------<br>";
echo"each=<pre>";
print_r(each($colors));
echo"</pre>";
?>

The iterator functions are:

Sr. Function Description


No.
1) current() Returns the element currently pointed at by the iterator
2) reset() Moves the iterator to the first element in the array and
returns it
3) next() Moves the iterator to the next element in the array and
returns it
4) prev() Moves the iterator to the previous element in the array
and returns it

5) end() Moves the iterator to the last element in the array and
returns it
6) each() Returns the key and value of the current element as an
array and moves the iterator to the next element in the
array

Unit II
Arrays, Functions and Graphics Page 22
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

7) key() Returns the key of the current element

2.4 Functions
A function is a block of statements that can be used repeatedly in a program. A
function will not execute immediately when page loads. A function will be executed
by a call to the function.

1) User Defined Function:


 A user defined function declaration starts with the word "function―.A function
name can start with a letter or underscore (not a number).

 Syntax
function functionName()
{
code to be executed;
}
functionName(); -----------Function call

 Example
<?php
function writeMsg( )
{
echo "Hello world!";
}
writeMsg(); // call the function
?>

 Output
Hello world!

2) Parameterized Function:
 PHP gives you option to pass your parameters inside a function. You can pass as
many as parameters your like. These parameters work like variables inside your
function. Following example takes two integer parameters and add them together
and then print them.

 Syntax
function functionName(variable1,variable2…)
{
code to be executed;
}

Unit II
Arrays, Functions and Graphics Page 23
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

functionName(variable1,variable2…); -----------Function call

 Example
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}

addFunction(10, 20);
?>

 Output
Sum of the two numbers is : 30

3) Return Type Function:


 A function can return a value using the return statement. return stops the
execution of the function and sends the value back to the calling code.

 Syntax
function functionName()
{
code to be executed;
return value;
}
Value=functionName(); -----------Function call

 Example
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value";
?>
 Output
Returned value from the function : 30
4) 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.
 Syntax
Unit II
Arrays, Functions and Graphics Page 24
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

function functionName()
{
code to be executed;
}
$variableName=‖functionName‖;
$variableName(); -----------Function call

 Example
<?php
function add($x, $y){
echo $x+$y;
}
$var="add";
$var(10,20);
?>

 Output
30

Anonymous Function:
 Anonymous function is a function without any user defined name. Such a
5) function is also called closure or lambda function. Sometimes, you may want a
function for one time use. Closure is an anonymous function which closes over
the environment in which it is defined. You need to specify use keyword in
it.Most common use of anonymous function to create an inline callback function.
 There is no function name between the function keyword and the opening
parenthesis.
 There is a semicolon after the function definition because anonymous function
definitions are expressions
 Function is assigned to a variable, and called later using the variable‘s name.
 When passed to another function that can then call it later, it is known as a
callback.
 Return it from within an outer function so that it can access the outer function‘s
variables. This is known as a closure.

 Syntax
$variableName=function ($arg1, $arg2)
{
return $val;
};
$variableName(); -----------Function call

Unit II
Arrays, Functions and Graphics Page 25
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 Example
<?php
$var = function ($x)
{
return pow($x,3);
};
echo "cube of 3 = " . $var(3);
?>

 Output
cube of 3 = 27

Function with default Arguments:


 If we call a PHP function without arguments, PHP functions takes the default
6) value as an argument

 Syntax
function functionName(variable1, variable2)
{
code to be executed;
}
$variableName=‖functionName‖;
$variableName(); ------Both arguments default
$variableName(variable1); ------variable2 is default
$variableName( ,variable2); ------variable1 is default

 Example
<?php
function weightHeight($defaultweight = 60,$defaultheight = 170) {
echo "The Weight is : $defaultweight <br>";
echo "The Height is : $defaultheight <br><br>";
}
weightHeight(45);
weightHeight();
weightHeight(70,160);
?>
 Output
The Weight is : 45
The Height is : 170

The Weight is : 60
The Height is : 170

Unit II
Arrays, Functions and Graphics Page 26
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

The Weight is : 70
The Height is : 160

2.5 String
 A string is a series of characters. There are exactly 256 different characters
possible.
 The string, like a variable, will have to be created first. There are two ways to use
a string in PHP – you can store it in a function or in a variable. In the example
below, we will create a string twice – the first time storing it in a variable, and the
second time – in a function, in our case – an echo
 Basic Example
<?php
$myString = "This is a string!";
echo "This is a string!</br>";
echo $myString;
?>
 The output of this PHP file will be:
This is a string!
This is a string!

String Functions:
1)
Str_word_count():
 The str_word_count() function counts the number of words in a string.

 Syntax
str_word_count(string,return,char)

 Parameters
1) string - Required. Specifies the string to check
2) return Optional. Specifies the return value of the str_word_count() function.
Possible values:
 0 - Default. Returns the number of words found
 1 - Returns an array with the words from the string
 2 - Returns an array where the key is the position of the word in the
string, and value is the actual word
3) char Optional. Specifies special characters to be considered as words.

 Example
<?php
echo"<pre>";
print_r(str_word_count("Hello world!"));
echo"</br>";
print_r(str_word_count("Hello world!",1));
Unit II
Arrays, Functions and Graphics Page 27
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

echo"</br>";
print_r(str_word_count("Hello world !",2,"!"));
echo"</br>";
print_r(str_word_count("Hello world !",0,"!"));
echo"</br>";
echo"</pre>";
?>
 Output
2
Array
(
[0] => Hello
[1] => world
)

Array
(
[0] => Hello
[6] => world
[12] => !
)

Strlen():
 The strlen() function returns the length of a string.

 Syntax
strlen(string)

 Parameters
string - Required. Specifies the string to check

 Example
<?php
echo strlen("Hello world!");
?>
 Output
12

Strlen():
 The strrev() function reverses a string.

 Syntax

Unit II
Arrays, Functions and Graphics Page 28
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

strrev(string)

 Parameters
string - Required. Specifies the string to check

 Example
<?php
echo strrev("Hello world!");
?>

 Output
!dlrow olleH

Strpos():
 The strpos() function finds the position of the first occurrence of a string inside
another string. The strpos() function is case-sensitive.
 strrpos() - Finds the position of the last occurrence of a string inside another
string (case-sensitive)
 stripos() - Finds the position of the first occurrence of a string inside another
string (case-insensitive)
 strripos() - Finds the position of the last occurrence of a string inside another
string (case-insensitive)

 Syntax
strpos(string,find,start)
strrpos(string,find,start)
stripos(string,find,start)
strripos(string,find,start)

 Parameters
1) string - Required. Specifies the string to check
2) find Required. Specifies the string to find
3) start Optional. Specifies where to begin the search. If start is a negative
number, it counts from the end of the string.

 Example
<?php
$str="Hello world!!! Good morning World. world is beautiful";
echo strpos($str,Hello)."</br>";
echo strrpos($str,world)."</br>";
echo stripos($str,Is)."</br>";
echo strripos($str,world,3)."</br>";
?>

Unit II
Arrays, Functions and Graphics Page 29
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 Output
0
35
41
35

Strstr_replace():
 The str_replace() function replaces some characters with some other
characters in a string.
 This function works by the following rules:
1) If the string to be searched is an array, it returns an array
2) If the string to be searched is an array, find and replace is performed with
every array element
3) If both find and replace are arrays, and replace has fewer elements than
find, an empty string will be used as replace
4) If find is an array and replace is a string, the replace string will be used
for every find value
 Syntax
str_replace(find,replace,string,count)

 Parameters
find- Required. Specifies the value to find
replace- Required. Specifies the value to replace the value in find
string- Required. Specifies the string to be searched
count- Optional. A variable that counts the number of replacements

 Example
<?php
echo ―Search an array for the value RED, and then replace it with pink‖;
$arr = array("blue","red","green","yellow");
$arr2=array("RGB");
$arr3=array("blue","red","green");
print_r(str_replace("red","pink",$arr,$i));
echo "<br>" . "Replacements: $i</br>";
print_r(str_replace($arr3,$arr2,$arr));
?>
 Output
Search an array for the value RED, and then replace it with pink.
Array ( [0] => blue [1] => pink [2] => green [3] => yellow )
Replacements: 1
Array ( [0] => RGB [1] => [2] => [3] => yellow )

ucwords():

Unit II
Arrays, Functions and Graphics Page 30
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 The ucwords() function converts the first character of each word in a string to
uppercase..

 Syntax
ucwords(string, delimiters)

 Parameters
string -Required. Specifies the string to convert
delimiters-Optional. Specifies the word separator character

 Example
<?php
echo ucwords("hello|world", "|")."</br>";
echo ucwords("hello world");
 ?>

 Output
Hello|World
Hello World

Strtoupper():
 The strtoupper() function converts a string to uppercase.

 Syntax
strtoupper(string)

 Parameters
string - Required. Specifies the string to convert.

 Example
<?php
echo strtoupper("hello world");
?>

 Output
HELLO WORLD

Strtolower():

 The strtolower() function converts a string to lowercase.

 Syntax
strtolower(string)

 Parameters
Unit II
Arrays, Functions and Graphics Page 31
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

string - Required. Specifies the string to convert.

 Example
<?php
echo strtolower("HELLO WORLD");
?>

 Output
hello world

Strcmp():
 The strcmp() function compares two strings.
 The strcmp() function is binary-safe and case-sensitive.
 This function is similar to the strncmp() function, with the difference that you can
specify the number of characters from each string to be used in the comparison
with strncmp().
 The strcasecmp() function compares two strings and it is case-insensitive.
 This function is similar to the strncasecmp() function, with the difference that you
can specify the number of characters from each string to be used in the
comparison with strncasecmp().

 Syntax
strcmp(string1,string2)
strcasecmp(string1,string2)
strncasecmp(string1,string2,length)

 Parameters
strcmp:
string1 Required. Specifies the first string to compare
string2 Required. Specifies the second string to compare

strncmp:
string1 Required. Specifies the first string to compare
string2 Required. Specifies the second string to compare
length Required. Specify the number of characters from each string to be
used in the comparison
 Return Value:
This function returns:
1) 0 - if the two strings are equal
2) <0 - if string1 is less than string2
3) >0 - if string1 is greater than string2

 Example
<?php
Unit II
Arrays, Functions and Graphics Page 32
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

echo strcmp("Hello","Hello");
echo "<br>";
echo strcmp("Hello","hELLo");
?>

<?php
echo strncmp("Hello","Hello",6);
echo "<br>";
echo strncmp("Hello","hELLo",6);
?>

 Output
0
-32

0
-32

lcfirst():
 The lcfirst() function converts the first character of a string to lowercase.

 Syntax
lcfirst(string)

 Parameters
string -Required. Specifies the string to convert

 Example
<?php
echo lcfirst("Good Morning");
echo "<br>";
echo lcfirst("good Morning");
?>

 Output
good Morning
good Morning

2.6 Basic Graphics Function.


PHP can be used to create and manipulate graphical elements independently.
Therefore, the scope and capabilities of PHP graphic handling are very powerful.
It does this with the aid of the GD library, which currently supports image formats in
jpeg, png, gif, and wbmp.

Unit II
Arrays, Functions and Graphics Page 33
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

1. Creating Image
We can create an image in PHP using imagecreate() function.
Syntax
$image=imagecreate(width,height)
2.
imagecolorallocate() function:-
The imagecolorallocate() function is an inbuilt function in PHP
which is used to set the color in an image. This function returns a color which is
given in RGB format.
Syntax:
imagecolorallocate ( $image, $red, $green, $blue )
Example
<?php
header ("Content-type: image/png");
$a = ImageCreate (200, 200);//imagecreate(x_size, y_size);
$bg = ImageColorAllocate ($a, 240, 0,0);
//imagecolorallocate(image, red, green, blue)
$txt_color = ImageColorAllocate ($a, 0, 23, 0);
ImageString ($a, 10, 10, 18, "Vesp Chembur Mumbai", $txt_color);//bool
imagestring( $image,
$font, $x, $y, $string, $color )
imagepng($a);s
?>

3. Scaling Images:-
 Scaling an image means making the image either smaller in size or larger in size
than original.
 Using PHP we can resize or rescale the image using the function Imagescale()
 Syntax:
imagescale($image,$new_width,$new_height=1,$mode=IMG_BILINERA_FIX
ED)
 Parameters:
 $image is returned by one of the image creation function.
 $new_width holds the width to scale the image.
 $new_height holds the height to scale the image.
 If the value of this parameter is negative or ommitted then aspect ration of
image will preserve.$mode holds the mode. The value of this parameter is
one of IMG_NEAREST_NEIGHBOUR, IMG_BILINEAR_FIXED,
IMG_BICUBIC, IMG_BICUBIC_FIXED ...

Unit II
Arrays, Functions and Graphics Page 34
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

Creation of PDF document


FPDF is an open source library which is used for creating a PDF document.it is open
source.Link to Download latest version of FPDF class:
http://www.fpdf.org/en/download.php

Features of fpdf
1)It is an open source package,hence freely available on internet
2)It provides the choice of measure unit,page format and margins for pdf page
3)It provides page header and footer management.
4)It provides automatic page breaks to the pdf document
5)It provides the support for various fonts,colors,encoding and image formate.
Example
<?php
require('fpdf183/fpdf.php');
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(60,10,'Hello PHP World!',1,1,'C');
$pdf->Output();
?>

Function use

1. $pdf=new FPDF("L", "mm", "A4");


 L(landscape default), P can be used instead to default to portrait pages.
 mm:-default measurement unit, a choice of point (pt), millimeter (mm),
centimeter (cm) and inch (in)
 size of the page, the choice of A3, A4, A5, Letter & Legal is given.

2. $pdf->AddPage();
Simple function, just add the page, you can tell the function to create either a
portrait (P) or landscape (L) by giving it as a first value (ex: $pdf-
>AddPage("L"), $pdf->AddPage("P")).

3. $pdf->SetFont('Arial','BIU',38);
 font:- Arial,
 BIU' simply tells that we want it to be Bold, Italic & Underlined.
 38 mm in size (because of the default size unit).

4. $pdf->SetTextColor(0,0,255);
color :- red (r), the second is green (g) & blue (b).

5. $pdf->Cell(60,20,'PDF+PHP Test',0,1,C,0);
 mm of width & 20 mm of height,
 String:- ‗PDF+PHP Test‘
Unit II
Arrays, Functions and Graphics Page 35
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 Border: 0 means we do not want a border.


 Line position:The 1 next to it means it will go to the beginning of the
next line, if 0 is provided, then it will be to the right of it, if 2 is
provided then it will go below.
 Alignment:The C is just the alignment which is the center of the text
inside the box, possible values are left (L), center (C), right (R).

6. $pdf->Output();
Output a new colorful PDF file!

Unit II
Arrays, Functions and Graphics Page 36

You might also like