Page 170 - Open Soource Technologies 304.indd
P. 170
Web Technologies-I
Notes 7.6.3 Filtering Elements from an Array
To identify a subset of an array based on its values, use the array_filter( ) 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. For example:
function is_odd ($element) { return $element % 2; } $numbers = array(9, 23, 24, 27); $odds =
array_filter($numbers, ‘is_odd’); // $odds is array(0 => 9, 1 => 23, 3 => 27)
7.6.4 Calculating the difference between Two Arrays
The array_diff( ) function identifies values from one array that are not present in others:
$diff = array_diff(array1, array2 [, array ... ]);
For example:
$a1 = array(‘bill’, ‘claire’, ‘elle’, ‘simon’, ‘judy’);
$a2 = array(‘jack’, ‘claire’, ‘toni’);
$a3 = array(‘elle’, ‘simon’, ‘garfunkel’); // find values of $a1 not in $a2 or $a3 $diff = array_
diff($a1, $a2, $a3); // $diff is array(‘bill’, ‘judy’);
Values are compared using ===, so 1 and “1” are considered different. The keys of the first array
are preserved, so in $diff the key of ‘bill’ is 0 and the key of ‘judy’ is 4.
7.7 Using Arrays
Arrays crop up in almost every PHP program. In addition to their obvious use for storing
collections of values, they’re also used to implement various abstract data types. In this, we
show how to use arrays to implement sets and stacks.
7.7.1 Stacks
Although not as common in PHP programs as in other programs, one fairly common data type is
the last-in first-out (LIFO) stack. We can create stacks using a pair of PHP functions, array_push(
) and array_pop( ). The array_push( ) function is identical to an assignment to $array[]. We use
array_push( ) because it accentuates the fact that we’re working with stacks, and the parallelism
with array_pop() makes our code easier to read. There are also array_shift( ) and array_unshift
( ) functions for treating an array like a queue.
Stacks are particularly useful for maintaining state. Example provides a simple state debugger
that allows you to print out a list of which functions have been called up to this point (i.e. the
stack trace).
State debugger
$call_trace = array( );
function enter_function($name) {
global $call_trace;
array_push($call_trace, $name); // same as $call_trace[] = $name
164 LOVELY PROFESSIONAL UNIVERSITY