Using an incremental index

suggest change

This method works by incrementing an integer from 0 to the greatest index in the array.

$colors = ['red', 'yellow', 'blue', 'green'];
for ($i = 0; $i < count($colors); $i++) {
    echo 'I am the color ' . $colors[$i] . '<br>';
}

This also allows iterating an array in reverse order without using array_reverse, which may result in overhead if the array is large.

$colors = ['red', 'yellow', 'blue', 'green'];
for ($i = count($colors) - 1; $i >= 0; $i--) {
    echo 'I am the color ' . $colors[$i] . '<br>';
}

You can skip or rewind the index easily using this method.

$array = ["alpha", "beta", "gamma", "delta", "epsilon"];
for ($i = 0; $i < count($array); $i++) {
    echo $array[$i], PHP_EOL;
    if ($array[$i] === "gamma") {
        $array[$i] = "zeta";
        $i -= 2;
    } elseif ($array[$i] === "zeta") {
        $i++;
    }
}

Output:

alpha
beta
gamma
beta
zeta
epsilon

For arrays that do not have incremental indices (including arrays with indices in reverse order, e.g. [1 => "foo", 0 => "bar"], ["foo" => "f", "bar" => "b"]), this cannot be done directly. array_values or array_keys can be used instead:

$array = ["a" => "alpha", "b" => "beta", "c" => "gamma", "d" => "delta"];
$keys = array_keys($array);
for ($i = 0; $i < count($array); $i++) {
    $key = $keys[$i];
    $value = $array[$key];
    echo "$value is $key\n";
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Array iteration:
* Using an incremental index

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
79 Array iteration
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR