Chapter-2(WBP)
Chapter-2(WBP)
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.
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)
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)
Example:
<?php
$name = array(19=> ―Arpan‖, ―Charmi‖, ―Reshma‖);
print_r($name);
?>
Output:
Array ([19]=> Arpan [20]=>Charmi [21]=>Reshma)
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)
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)
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_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)
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.
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?";
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?
)
Array
(
[0] => Hello, How can we help you?
)
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)
Example:
<?php
$KR="KARNATAKA";
$state = array("AS"=>"ASSAM", "OR"=>"ORISSA", "KR"=>"KERALA");
echo $KR."</br>";
echo"</br>";
extract($state);
Output:
KARNATAKA
Unit II
Arrays, Functions and Graphics Page 17
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
KERALA
ORISSA
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";
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
)
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 )
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 )
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)
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 )
Example:
<?php
$colors = array("red", "green", "blue", "yellow");
echo"Array Elements are<br>"; Output :
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)
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.
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)
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
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
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():
Syntax
strtolower(string)
Parameters
Unit II
Arrays, Functions and Graphics Page 31
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
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
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)
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
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)
6. $pdf->Output();
Output a new colorful PDF file!
Unit II
Arrays, Functions and Graphics Page 36