PHP foreach: first & last elements of an array
Sometimes you need to identify the first and last elements of an array for use in a foreach loop. And in PHP this looks set to get a whole lot easier thanks to the new version 7.3, which is currently at Release Candidate status.
In previous versions of PHP you would’ve had to do something like this:
// Go to start of array and get key, for later comparison
reset($array)
$firstkey = key($array);
// Go to end of array and get key, for later comparison
end($array);
$lastkey = key($array);
foreach ($array as $key => $element) {
// If first element in array
if ($key === $firstkey)
echo 'FIRST ELEMENT = '.$element;
// If last element in array
if ($key === $lastkey)
echo 'LAST ELEMENT = '.$element;
} // end foreach
Now in PHP 7.3 and up, there are new functions called array_key_first
and array_key_last
, so you just need to call those:
foreach($array as $key => $element) {
// If first element in array
if ($key === array_key_first($array))
echo 'FIRST ELEMENT = '.$element;
// If last element in array
if ($key === array_key_last($array))
echo 'LAST ELEMENT = '.$element;
} // end foreach
If nothing else it certainly makes for much neater code.