PHP | A more elegant way to loop through with an index

Vaqar
app dev
Published in
2 min readMay 2, 2019

In past, I would loop through an array using foreach most of the time. Occasionally a for loop and hardly any while loop in PHP. If I ever needed an index of a loop I would still use foreach loop with a declaration of $index variable before the loop and a $index++ at the end of loop thus giving me a number of the loop in $index variable.

$myArray = array('a' => 'one', 'b' => 'two', 'c' => 'three');$index = 0;
foreach($myArray as $element) {
echo $index . ': ' . $element. PHP_EOL;
$index++;
}

This example looks pretty clean and it works but a much better and elegant way is to use while loop with array pointers to iterate and print index.

while (key($myArray) !== null)
{
echo key($myArray) . ': ' . current($myArray) . PHP_EOL;
next($myArray);
}

In the example above, we are running loop while there is next array key available, no $index variable needs to be declared and incremented as key() and current() gives access to the key and value of the current element in the loop. next() increments array pointer to next value.

Array pointer by default is set to 0, we can use reset() to set it 0. To run a reverse loop use end() to set array pointer at the last element of an array and inside loop decrement instead of incrementing using prev().

While PHP while() loop might be an elegant solution, it is not the fastest when compared to other loops.

PHP Loops Benchmark — screenshot: phpbench.com

According to phpbench.com foreach loops are far better in performance than both while() and for() loops.

--

--