Chapter 3
PHP
Array part-3
1
Monica Deshmane(H.V.Desai college,Pune)
Topics
• Converting between arrays and variables
• Traversing arrays
• Iterator function
• Reducing an array
• flipping an array
• Array shuffle
• Acting on entire array
• Using arrays(set,stack,queue)
Monica Deshmane(H.V.Desai college,Pune) 2
Conversion
between
array and variable
Monica Deshmane(H.V.Desai college,Pune) 3
1. Creating variables from array
Which parameters required?
?
extract($arr, [ EXTR_PREFIXtype, prefix]);
Type can be -
EXTR_PREFIX_ALL
Third parameter is prefix for all variables
Can we extract indexed array?
No..
Monica Deshmane(H.V.Desai college,Pune) 4
Example
$arr = array('name'=>'C', 'author'=>'Dennis Richie',
'price'=>500);
extract($arr, EXTR_PREFIX_ALL, "book");
echo $book_name." ".$book_author." ".$book_price;
//C Dennis Richie 500
Monica Deshmane(H.V.Desai college,Pune) 5
2. Creating array from variables
Which parameters required?
?
List of variables
$arr = compact(var1,var2,…);
print_r($a);
Monica Deshmane(H.V.Desai college,Pune) 6
Example
$name = ' C';
$author='Dennis';
$price =500;
$a = compact('name', 'author', 'price');
print_r($a);
$arr = array('name', 'author', 'price');
$a=compact($arr);
echo "<br>";
print_r($a);
//Array ( [name] => C [author] => Dennis [price] => 500 )
//Array ( [name] => C [author] => Dennis [price] => 500 )
Monica Deshmane(H.V.Desai college,Pune) 7
Travesing arrays / locate elements in array
foreach -
$sub = array('C', 'CPP', 'Java', 'PHP', 'DS');
foreach($sub as $value)
{ echo $value. " ";
}
C CPP Java PHP DS
$book = array('C' => 'Richie' , 'CPP' => 'Bjarne', 'Java'
=> 'Sun', 'PHP'=>'Orelly');
foreach($book as $key=>$value)
{ echo $key." is ".$value." ";
}
C is Richie CPP is Bjarne Java is Sun PHP is Orelly
Monica Deshmane(H.V.Desai college,Pune) 8
Iterator function
current( ) - Returns the currently pointed element by the
iterator.
reset( ) - Moves the iterator to the first element in the
array and returns it.
next( ) - Moves the iterator to the next element in the
array and returns it.
prev( ) - Moves the iterator to the previous element in the
array and returns it.
end( ) - Moves the iterator to the last element in the array
and returns it.
each( ) - Returns the key and value of the current element
as an array and moves the iterator to the next element in
the array.
key( ) - Returns the key of the current element.
Monica Deshmane(H.V.Desai college,Pune) 9
Iterator function
$book = array('C' => 'Richie' , 'CPP' => 'Bjarne', 'Java'
=> 'Sun', 'PHP'=>'Orelly');
reset($book);
while(list($key, $value) = each($book))
{
echo $keys.” is “.$value;
}
Monica Deshmane(H.V.Desai college,Pune) 10
Calling a Function for Each Array Element
function print_row($value, $key)
{
echo $key." ".$value."<br>";
}
$book = array('C' => 'Richie' , 'CPP' => 'Bjarne', 'Java'
=> 'Sun', 'PHP'=>'Orelly');
array_walk($book, 'print_row');
C Richie
CPP Bjarne
Java Sun
PHP Orelly
Monica Deshmane(H.V.Desai college,Pune) 11
Question-
Which function returns all parameters passed to
function as an array?
Array_walk()
Monica Deshmane(H.V.Desai college,Pune) 12
Iterator function
Using for loop
$sub = array('C', 'CPP', 'Java', 'PHP', 'DS');
for($i = 0; $i < count($sub); $i++)
{
$value = $sub[$i];
echo "$valuen";
}
C CPP Java PHP DS
Monica Deshmane(H.V.Desai college,Pune) 13
Reducing an array
array_reduce: This also calls function on each element. It
returns single value.
Which parameters required?
?
$result = array_reduce(array, function_name [, default ]);
Default value is start value.
Monica Deshmane(H.V.Desai college,Pune) 14
Reducing an array
array_reduce: This also calls function on each element. It
returns single value.
$result = array_reduce(array, function_name [, default ]);
function add($v1,$v2)
{
return $v1+$v2;
}
$a=array(10,15,20);
print_r(array_reduce($a,"add"));
add(0, 10);
add(10, 15);
add(25, 20); Output: 45
Monica Deshmane(H.V.Desai college,Pune) 15
Reducing an array
We can pass initial value as third parameter
function add($v1,$v2)
{
return $v1+$v2;
}
$a=array(10,15,20);
print_r(array_reduce($a,"add", 5));
add(5, 10);
add(15, 15);
add(30, 20);
Output: 50
Monica Deshmane(H.V.Desai college,Pune) 16
Reversing an array
array_reverse(array,preserve)
preserve(optional) Specifies if the function should
preserve the array's keys or not.(true, false)
$book = array('C' => 'Richie' , 'CPP' => 'Bjarne', 'Java'
=> 'Sun', 'PHP'=>'Orelly');
$rev = array_reverse($book);
print_r($rev);
//Array ( [PHP] => Orelly [Java] => Sun [CPP] =>
Bjarne [C] => Richie )
Monica Deshmane(H.V.Desai college,Pune) 17
flipping an array
array_flip(array) - returns an array with all the
original keys as values, and all original values as
keys.
$book = array('C' => 'Richie' , 'CPP' => 'Bjarne', 'Java'
=> 'Sun', 'PHP'=>'Orelly');
$rev = array_flip($book);
print_r($rev);
//Array ( [Richie] => C [Bjarne] => CPP [Sun] =>
Java [Orelly] => PHP )
Monica Deshmane(H.V.Desai college,Pune) 18
Array shuffle
Jumbles the elements of array.
i.e. elements in array comes in random order.
Syntax:-
Shuffle(array1);
$arr=array(1,3,6,8);
print_r($arr);
shuffle($arr);
print_r($arr);
shuffle($arr);
print_r($arr);
//elements are shuffled in same array itself.
Monica Deshmane(H.V.Desai college,Pune) 19
Acting on entire array
Array_sum
Array_diff
Array_merge
Array_filter
Set-
array_intersect
array_merge
array_diff
stack=-array_push
array_pop
Queue-
array_unshift
array_shift
Monica Deshmane(H.V.Desai college,Pune)
20
Acting on entire array
Calculating the Sum of an Array
array_sum( ) - function adds up the values in an
indexed or associative array.
$sum = array_sum(array);
$marks = array(25, 37, 48, 90);
$total = array_sum($marks);
echo $total;
//200
Monica Deshmane(H.V.Desai college,Pune)
21
Acting on entire array
Merging two arrays
array_merge( ) - function intelligently merges two or
more arrays.
$merged = array_merge(array1, array2 [, array ... ])
$book1 = array('C' => 'Richie' , 'CPP' => 'Bjarne',
'Java' => 'Sun');
$book2 = array('C' => 'Dennis' , 'SDK' => 'Petzold',
'PHP'=>'Orelly');
$merged = array_merge($book1, $book2);
print_r($merged);
//Array ( [C] => Dennis [CPP] => Bjarne [Java] =>
Sun [SDK] => Petzold [PHP] => Orelly )
note-we can merge indexed and associative array
Monica Deshmane(H.V.Desai college,Pune) 22
Acting on entire array
Difference between two arrays
array_diff( ) - function identifies values from one
array that are not present in others.
$diff = array_diff(array1, array2 [, array ... ]);
$book1 = array('C' => 'Richie' , 'CPP' => 'Bjarne',
'Java' => 'Sun');
$book2 = array('C' => 'Dennis' , 'SDK' => 'Petzold',
'PHP'=>'Orelly', 'XML' => 'Wrox');
$book3 = array('XML' => 'Wrox' , 'CPP' => 'Bjarne',
'Unix' => 'Bach', 'SDK'=>'Petzold');
$diff = array_diff($book1, $book2, $book3);
print_r($diff);
Monica Deshmane(H.V.Desai college,Pune) 23
Acting on entire array
//Array ( [C] => Richie [Java] => Sun )
//also see example of indexed array.
Monica Deshmane(H.V.Desai college,Pune)
24
Acting on entire array
Filtering Elements from an Array
array_filter( ) - function is used to identify a subset of
an array based on its values.
Used to return subset according to function.
$filtered = array_filter(array, callback);
Each value of array is passed to the function named in
callback. The returned array contains only those
elements of the original array for which the function
returns a true value.
Monica Deshmane(H.V.Desai college,Pune) 25
Acting on entire array
Filtering Elements from an Array
function myfunction($v)
{
if ($v==="Blue")
{
return true;
}
return false;
}
$a=array(0=>"Red",1=>"Blue",2=>"Green");
print_r(array_filter($a,"myfunction"));
//Array ( [1] => Blue )
Monica Deshmane(H.V.Desai college,Pune) 26
Ex.2)
Function even($v)
{
if $v%2==0
return 1;
else
return 0;
}
$n=array(4,7,2,10,9);
print_r(array_filter($a,”even”));
Monica Deshmane(H.V.Desai college,Pune) 27
Using arrays – for sets
1. Union - The union of two sets is all the elements
from both sets, with duplicates removed. The
array_merge( ) and array_unique( ) functions let
you calculate the union.
2. Intersection - array_intersect( ) function takes any
number of arrays as arguments and returns an
array of those values that exist in each.
3. Difference - array_diff( ) function calculates this,
returning an array with values from the first array
that are not present in the second.
Monica Deshmane(H.V.Desai college,Pune) 28
Using arrays – for stacks
For growing or shrinking array stack /queue is used.
Stacks –LIFO
We can create stacks using a pair of PHP functions,
array_push( ) and array_pop( ).
1)array_push(array,val1,[val2,….]);
We can push 1 or more elements on top of stack.
$a=array(1,2);
array_push($a,5,4,3);
2)array_pop(array);
We can pop only 1 element from top of stack.
//consider above array
array_pop($a);
Monica Deshmane(H.V.Desai college,Pune) 29
Using arrays – for Queue
For growing or shrinking array stack /queue is used.
Queue –FIFO
We can create queue using a pair of PHP functions,
array_shift( ) and array_unshift( ).
1)array_unshift(array,val1,[val2,….]);
We can insert 1 or more elements in front of queue.
$a=array(1,2);
array_unshift($a,5,4,3);//see the order
2)Remainingarr=array_shift(array);
We can delete only 1 element from front of queue.
//consider above array
$rem=array_shift($a);
Monica Deshmane(H.V.Desai college,Pune) 30