This post covers the Array Interation section of the Arrays chapter when studying for the Zend PHP 7 Certification.
There are several ways that we can iterate over arrays. For numeric arrays, a simple for
loop might look like the below.
$numbers = array(0, 1, 2, 5, 10);
for ($i = 0; $i < count($numbers); $i++) {
echo $numbers[$i] . "\n";
}
// Outputs:
0
1
2
5
10
Similarly with foreach
loops, we can also extract the values of a numeric array.
$numbers = array(0, 1, 2, 5, 10);
foreach ($numbers as $number) {
echo $number . "\n";
}
// Outputs:
0
1
2
5
10
However for associative arrays, as the indexes do not have to be numeric, we have to use a foreach
loop. An example of a simple foreach
can be seen below.
$numbers = array("string" => "somestring", "number" => 1, 3 => 2, "somethingelse" => "test123", 10);
foreach ($numbers as $key => $value) {
echo "Key: $key; Value: $value<br />";
}
// Outputs:
Key: string; Value: somestring
Key: number; Value: 1
Key: 3; Value: 2
Key: somethingelse; Value: test123
Key: 4; Value: 10
An alternative of looping through associative arrays is using a while
loop using the list()
and each()
functions. The list()
function assigns variables as if they were an array.
$array = array('coffee', 'brown', 'caffeine');
// Listing all the variables
list($drink, $color, $power) = $array;
echo "$drink is $color and $power makes it special.\n";
The each()
function returns the current key and value pair from an array and advance the array cursor. This pair is returned in a four-element array, with the keys 0, 1, key, and value. Elements 0 and key contain the key name of the array element, and 1 and value contain the data.
<?php
$foo = array("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each($foo);
print_r($bar);
// Outputs:
Array
(
[1] => bob
[value] => bob
[0] => 0
[key] => 0
)
With that said, we can use both functions in a while
loop like the below.
<?php
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');
reset($fruit);
while (list($key, $val) = each($fruit)) {
echo "$key => $val\n";
}
The list/each combination is functionally identical to the foreach
loop example above, however the foreach
loop has been proven to be faster, so it's recommended to use this.
In fact, as of PHP version 7.2, the each()
function is deprecated and using the function is highly discouraged.
Another change within PHP 7.0 is that the list()
now assigns the values starting with the right-most parameter rather than the left.
<?php
list($a[], $a[], $a[]) = [1, 2, 3];
var_dump($a);
// Output prior to PHP 7
array(3) { [0]=> int(3) [1]=> int(2) [2]=> int(1) }
// Output in PHP 7+
array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }
Some other array iteration functions, such as array_walk()
, applies a user supplied function to every member of an array.
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
function test_print($item2, $key)
{
echo "$key. $item2
\n";
}
array_walk($fruits, 'test_print');
// Outputs:
d. lemon
a. orange
b. banana
c. apple
When iterating over arrays, PHP provides us with functions to check whether certain keys or values exist within the array.
The array_key_exists()
checks if the given key or index exists in the array.
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
in_array()
checks if a value exists in an array.
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
if (in_array("mac", $os)) {
echo "Got mac";
}
Note that the second condition fails as in_array()
is case sensitive.
The array_keys()
function returns all the keys or a subset of the keys of an array.
<?php
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
// Outputs:
Array
(
[0] => 0
[1] => color
)
Similarly, array_values()
returns all the values of an array.
<?php
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
// Outputs:
Array
(
[0] => XL
[1] => gold
)
View the other sections:
Note: This article is based on PHP version 7.0.