Arrays
as Stacks, Queues and Sets
Arrays are often used as stacks
(Last In, First Out, or LIFO) and queue (First In, First Out, or FIFO)
structures. PHP simplifies this approach by providing a set of functions can be
used to push and pull (for stacks) and shift and unshift (for queues) elements from
an array.
We’ll take a look at stacks first:
$stack = array();
array_push($stack, ’bar’, ’baz’);
var_dump($stack);
$last_in = array_pop($stack);
var_dump($last_in, $stack);
In this example, we first, create an
array, and we then add two elements to it using array_push(). Next, using array_pop(),
we extract the last element added to the array, resulting in this output:
array(2) {
[0]=>
string(3) "bar"
[1]=>
string(3) "baz"
}
string(3) "baz"
array(1) {
[0]=>
string(3) "bar"
}
If you intend to use an array as a
queue, you can add elements to the beginning and
extract them from the end by using
the array_unshift() and array_shift() func-tions:
$stack = array(’qux’, ’bar’, ’baz’);
$first_element = array_shift($stack);
var_dump($stack);
array_unshift($stack, ’foo’);
var_dump($stack);
In this example, we use array_shift()
to push the first element out of the array. Next,
using array_unshift(), we do the
reverse and add a value to the beginning of the
array. This example results in:
array(2) {
[0]=>
string(3) "bar"
[1]=>
string(3) "baz"
}
array(3) {
[0]=>
string(3) "foo"
[1]=>
string(3) "bar"
[2]=>
string(3) "baz"
}
Set
Functionality
Some PHP functions are designed to
perform set operations on arrays. For example, array_diff() is used to compute
the difference between two arrays:
$a = array (1, 2, 3);
$b = array (1, 3, 4);
var_dump (array_diff ($a, $b));
The call to array_diff() in the code
above will cause all the values of $a that do not also appear in $b to be
retained, while everything else is discarded:
array(1) {
[1]=>
int(2)
}
Note that the keys are ignored—if you
want the difference to be computed based on key-value pairs, you will have to
use array_diff_assoc() instead, whereas if you want it to be computed on keys
alone, array_diff_key() will do the trick. Both of these functions have
user-defined callback versions called array_diff_uassoc() and array_diff_ukey()
respectively.
Conversely to array_diff(), array_intersect()
will compute the intersection between two arrays:
$a = array (1, 2, 3);
$b = array (1, 3, 4);
var_dump (array_intersect ($a, $b));
In this case, only the values that
are included in both arrays are retained in the result:
array(2) {
[0]=>
int(1)
[2]=>
int(3)
}
Like with array_diff(), array_intersect
only keeps in consideration the value of each element; PHP provides array_intersect_key()
and array_intersect_assoc() versions for key- and key/value-based intersection,
together with their callback variants array_intersect_ukey() and array_intersect_uassoc().
0 Comment to " PHP Arrays as Stacks, Queues and Sets "
Post a Comment