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:



Table Of Contents