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 section, we show how to use arrays to implement sets and stacks.
Sets
Arrays let you implement the basic operations of set theory: union, intersection, and difference. Each set is represented by an array, and various PHP functions implement the set operations. The values in the set are the values in the array—the keys are not used, but they are generally preserved by the operations.
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. Here’s how to find the union of two arrays:
function
arrayUnion
(
$a
,
$b
)
{
$union
=
array_merge
(
$a
,
$b
);
// duplicates may still exist
$union
=
array_unique
(
$union
);
return
$union
;
}
$first
=
array
(
1
,
"two"
,
3
);
$second
=
array
(
"two"
,
"three"
,
"four"
);
$union
=
arrayUnion
(
$first
,
$second
);
print_r
(
$union
);
Array
(
[
0
]
=>
1
[
1
]
=>
two
[
2
]
=>
3
[
4
]
=>
three
[
5
]
=>
four
)
The intersection of two sets is the set
of elements they have in common. PHP’s built-in array_intersect()
function takes any number of
arrays as arguments and returns an array of those values that exist in
each. If multiple keys have the same value, the first key with that
value is preserved.
Stacks
Although not as common in PHP programs as in other programs, one fairly common data type is the last-in ...
Get Programming PHP, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.