PHP Array iteration edit

Using an incremental index

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:


Table Of Contents
15 JSON
16 SOAP
18 cURL
20 XML
37 URLs
73 YAML
80 Array iteration
82 PDO
94 IMAP
103 APCu
109 PSR
  ↑ ↓ to navigate     ↵ to select     Esc to close