Wondering what would be a good method to get the first iteration on a foreach loop. I want to do something different on the first iteration.
Is a conditional our best option on these cases?
Method 3: The reset() function is used to find the first iteration in foreach loop. When there is no next element is available in an array then it will be the last iteration and it is calculated by next() function.
In short: foreach is faster than foreach with reference.
Use count() to determine the total length of an array. The iteration of the counter was placed at the bottom of the foreach() loop - $x++; to execute the condition to get the first item. To get the last item, check if the $x is equal to the total length of the array. If true , then it gets the last item.
Yes, if you are not able to go through the object in a different way (a normal for loop), just use a conditional in this case:
$first = true; foreach ( $obj as $value ) { if ( $first ) { // do something $first = false; } else { // do something } // do something }
Even morer eleganterer:
foreach($array as $index => $value) { if ($index == 0) { echo $array[$index]; } }
That example only works if you use PHP's built-in array append features/function or manually specify keys in proper numerical order.
Here's an approach that is not like the others listed here that should work via the natural order of any PHP array.
$first = array_shift($array); //do stuff with $first foreach($array as $elem) { //do stuff with rest of array elements } array_unshift($array, $first); //return first element to top
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With