WBP-02 j1
WBP-02 j1
2.2 Extracting data from arrays, implode. Explode, and array flip.
2.4 Function and its types - User defined function, variable function and
anonymous function.
2.6 Basic Graphics Concepts, creating Images, Images with text, Scaling Images,
Creation of PDF document.
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in
single variables could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
However, what if you want to loop through the cars and find a specific one? And
what if you had not 3 cars, but 300?
The solution is to create an array!
An array can hold many values under a single name, and you can access the
values by referring to an index number.
Array:
Example
<?php
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Types of array
There are three different kind of arrays and each array value is accessed using an
ID which is called array index.
Numeric array − An array with a numeric index. Values are stored and accessed
in linear fashion.
Associative array − An array with strings as index. This stores element values in
association with key values rather than in a strict linear index order.
Multidimensional array − An array containing one or more arrays and values are
accessed using multiple indices
PHP Indexed Arrays
An array with a numeric index. Values are stored and accessed in linear fashion.
Numeric array uses numbers as access key.
An access key is a reference to a memory slot in an array variable.
The access key is used whenever we want to read or assign a new value to an
array element.
Syntax for creating indexed array in php
<?php
$variable_name[n]=value;
?>
Where
variable_name- is the name of the variable
[n] is the access index number of the element
value is the value assigned to the array element
Indexed array
There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0), like this:
$subjects = array("JAVA", "PHP”, "Android");
or the index can be assigned manually:
$subjects[0] = "JAVA";
$subjects[1] = "PHP";
$subjects[2] = "Android";
The following example creates an indexed array named $subjects, assigns three
elements to it, and then prints a text containing the array values:
Example
<?php
$subjects = array("JAVA", "PHP", "Android");
echo "I like " . $subjects[0] . ", " . $subjects[1] . " and " . $subjects[2] . ".";
?>
Associative Arrays
● The associative arrays are very similar to numeric arrays in term
of functionality 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.
● To store the salaries of employees in an array, a numerically
indexed array would not be the best choice.
● Instead, we could use the employees names as the keys in our
associative array, and the value would be their respective salary.
● Don't keep associative array inside double quote while printing
otherwise it would not return any value .
Associative Arrays
Syntax of associative array in php
<?php
$variable_name[‘key_name’]=value;
$variable_name=array(‘keyname’=>value);
?>
Where
“$variable_name”- is the name of the variable
“[‘key_name’]” is the access index number of the element
“value” is the value assigned to the array element
Example:
<?php
$capital=array(“Mumbai”=> “Maharashtra”, “Goa”=> “Panji”,”Bihar”=>”Patna”);
print_r($capital);
echo”<br>”;
echo “Mumbai is a capital of “.$capital [“Mumbai”];
?>
Associative Arrays
print_r() is used for displaying the contents of an array.
By default, array starts with index 0.
If we want to start index with 1 use PHP=>operator
$course=array(1 => ”Computer Engg”, 2 => ”Information Tech”, 3
=> “Electronics and tele”);
The => operator create key/value pairs in arrays.
The item on the left of the operator => is the key and the item on
the right is the value.
Multidimensional Arrays
● A multidimensional array each element in the main array can
also be an array.
● And each element in the sub-array can be an array, and so on.
Values in the multi-dimensional array are accessed using
multiple index.
Example
● In this example we create a two dimensional array to store
marks of three students in three subjects −
● This example is an associative array, you can create numeric
array in the same fashion.
Syntax
array(
array (elements…),
array (elements…),
)
Extracting data from arrays
● The extract() Function is an inbuilt function in PHP.
● The extract() function convert array to variable.
● That is it converts array keys into variable names and array
values into variable value.
● In other words, we can say that the extract() function imports
variables from an array to the symbol table.
Syntax:
extract($input_array)
Example
<?php
// input array
$state = array("AS"=>"ASSAM", "OR"=>"ORISA",
"KR"=>"KERLA");
extract($state);
// after using extract() function
echo"\$AS is $AS\n\$KR is $KR\n\$OR is $OR";
?>
PHP list() Function
Assign variables as if they were an array:
<?php
$my_array = array("Dog","Cat","Horse");
list($a, $b, $c) = $my_array;
echo "I have several animals, a $a, a $b and a $c.";
?>
O/p
I have several animals, a Dog, a Cat and a Horse.
PHP compact() Function
Create an array from variables and their values:
<?php
$firstname = "Peter";
$lastname = "Griffin";
$age = "41";
$result = compact("firstname", "lastname", "age");
print_r($result);
?>
O/p-
Array ( [firstname] => Peter [lastname] => Griffin [age] => 41 )
Implode and Explode
Imploding exploding are couple of important functions of PHP
that can be applied on strings or arrays.
Syntax
implode(separator,array)
Parameter Description
echo $comma_separated;
?>
o/p:lastname,email,phone
explode() Function
The explode() function breaks a string into an array.
The "separator" parameter cannot be an empty string.
Syntax:
explode(separator,string,limit)
Parameter Values
Parameter Description
separator Required. Specifies where to break the string
string Required. The string to split
limit Optional. Specifies the number of array elements to
return.
Possible values:
Greater than 0 - Returns an array with a maximum of limit element(s)
Less than 0 - Returns an array except for the last -limit elements()
explode() Function
Break a string into an array:
<?php
?>
o/p:Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] =>
beautiful [5] => day. )
array_flip() Function
The array_flip() function flips/exchanges all keys with their
associated values in an array.
Syntax
array_flip(array)
Parameter Description
o/p:Array([red]=>a[green]=>b[blue]=>c[yellow]=>d)
Example
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$result=array_flip($a1);
echo($result);
?>
TRAVERSING ARRAYS
● Traversing: We can traverse an indexed array using loops in PHP.
● We can loop through the indexed array in two ways.
● First by using for loop and secondly by using foreach.
● PHP provides several ways to traverse arrays using both array iteration
functions and language constructs: foreach, list/each, and for loops.
foreach
PHP's foreach loop provides a convenient way to iterate over arrays.
There are two forms: one uses both the key and value of each array entry while
the other uses only the value.
First we demonstrate the key => value form:
$pets = ['Morie', 'Miki', 'Halo', 'lab' => 'Winnie'];
foreach ($pets as $key => $val) {
echo "$key => $val \n";
}
//output
0 => Morie
1 => Miki
2 => Halo
lab => Winnie
Using for loop
The for loop operates on the array itself,not on copy of array
Example:
$a=array(1,2,3,4);
for($i=0;$i<count($a);$i++)
echo $a[i].”<br>”
}
Iteration Function
Every php array keeps track of the current element.
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 return it
4.prev():Moves the iterator to the previous element in the array and return it.
.
5.end():moves the iterator to the last element in the array and return it.
6.each():Return the key and value of the current element as an array and moves
the iterator to the next element in the array
Example:
<php
$a=array(10,20,30,40,50);
reset($a);
while(list ($key,$val)=each($a))
{
echo "$key=>$val<br> ";
}
?>
o/p:
0=>10
1=>20…..4=>50
Function and its types -
● A function is a block of code written in a program to perform some specific
task.
● They take informations as parameter, executes a block of statements or
perform operations on this parameters and returns the result.
● PHP has over 1000 built-in functions that can be called directly, from within a
script, to perform a specific task.
● PHP gives you option to create your own functions.
● A function will be executed by a call to the function.
● You can call function from anywhere within a page.
There are two parts of functions-
● Creating a PHP function
● Calling a PHP function
User defined function
Create a User Defined Function in PHP : A user-defined function declaration starts
with the word function:
Syntax
function functionName() {
code to be executed;
}
Example
<?php
function writeMsg() {
echo "Welcome to PHP world!";
}
writeMsg(); // call the function
?>
PHP Function Arguments
Information can be passed to functions through arguments.
An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses.
You can add as many arguments as you want, just separate them with a comma.
Example:
<?php
Function addfunc($num1,$num2)
{
$num=$num1+$num2;
echo “Sum of the two numbers is : $num”;
}
addfunc(23,34);
?>
PHP functions returning value
A function can return value using the return statement in conjunction with a value
or object.
Return stops the execution of the function and sends the value back to the calling
code.
You can return more than one value from a function using return array(1,2,3,4)
<?php
function add($num1,$num2)
{
$sum=$num1+$num2;
return $sum;
}
$return_value=add(30,40);
echo "Returned value from the function $return_value";
?>
variable function
● PHP supports the concept of variable functions. This means that if a
variable name has parentheses appended to it, PHP will look for a
function with the same name as whatever the variable evaluates to,
and will attempt to execute it.
ex1):<?php
function writeMsg() {
echo “Welcome to PHP world!”;
}
$wrt= ”writeMsg”;
$wrt();// call the function
?>
ex2:
<?php
function writeMsg($name) {
echo "$name PHP world!";
}
$wrt="writeMsg";
$wrt("Hello");// call the function
?>
Anonymous function.
We can define a function that has no specified name.
We call this function is an anonymous function or closure. Also call as lambda
function.
-Can be stored in a variable
-Can be returned in a function
-Can be pass in a function
The anonymous function is created using the create_function().
It takes two parameters first parameter is the parameter list for anonymous
function and second parameter contains the actual code of the function.
ex:
1:<?php
$add=create_function(“$a,$b”,”return($a+$b);”);
$r=$add(2,3);
echo $r;
?>
EX:
<?php
//Normal Function
function show(){
echo “Normal Function”;
}
show();
//Anonymous Function
$a=function(){
echo “Anonymous Function”;
};
$a();
?>
<?php
//Anonymous Function
$y=34; //global
$a=function($p){
echo “Anonymous Function $p”;
};
$a($y);
?>
<?php
//Anonymous Function
$y=34; //global
$r=10; //global
$a=function($p) use ($r){
echo “Anonymous Function $r $p”;
};
$a($y);
?>
Operations on string and string functions
● PHP is a string oriented and having many string functions.
● A string is collection of characters.
● STring is one of the data type supported by PHP.
● The string variables can contain alphanumeric characters.
Creating a string:
There are two ways to create a string in php.
1. Create a string using single quotes
2. Create a string using double quotes.
str_word_count()
The PHP str_word_count() function counts the
number of words in a string.
syntax:str_word_count(string)
Example
<?php
echo str_word_count("Welcome to PHP world!");
?>
// outputs 4
strlen()
Returns the length of a string.
Syntax:
strlen($str)
Example:
<?php
echo strlen("Hello world!"); // outputs 12
?>
strrev()
The PHP strrev() function reverses a string.
Syntax:
strrev(string)
Example
Reverse the string "Hello world!":
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
strpos()
Syntax: strpos(string,text)
The PHP strpos() function searches for a specific text within a
string. If a match is found, the function returns the character
position of the first match. If no match is found, it will return
FALSE.
Example
Search for the text "world" in the string "Hello world!":
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
str_replace
str_replace(string to be replaced text,string)
The PHP str_replace() function replaces some
characters with some other characters in a string.
Example
Replace the text "world" with "Dolly":
<?php
echo str_replace("world", "Dolly", "Hello world!"); //
outputs Hello Dolly!
?>
strcmp()
Compare two strings (case-sensitive):
<?php
echo strcmp("Hello world!","Hello world!");
?>
ucwords() =ucwords($string,$separator)
strtoupper()=strtoupper($string)
strtolower()=strtolower($input_str)
Basic graphics concept
Creating Image
Syntax $image=imagecreate(width,height)
Step2:
The next step to send content-Type header to the browser with appropriate
content type for the kind of image being create.
imagejpeg($image);
header(‘content-Type:image/jpeg’);
imagecolorallocate() function
header(‘Content-Type:image.jpeg’);
imagejpeg($img)
Images with text
The imageString() method is used to add the text with image.
syntax:ImageString($image,$font,$x,$y,$text,$color)
$image: The imagecreate or imagecreatetruecolor() function is used to create an
image in a given size.
$font: This parameter is used to set the font size. Inbuilt font in latin2 encoding can
be 1,2,3,4,5 or other identifiers registered with imageloadfont() function.
$x: This parameter is used to hold the x-coordinator of upper left corner.
$y: This parameter is used to hold the x-coordinator of upper left corner.
Features of fpdf
2)it provides the choice of measure unit,page format and margins for pdf page
5)it provides the support for various fonts,colors,encoding and image formate.