Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Grab the first element using a foreach

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?

like image 752
MEM Avatar asked Oct 18 '10 09:10

MEM


People also ask

How do you get the first value in foreach?

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.

Is foreach faster than for PHP?

In short: foreach is faster than foreach with reference.

How do you get to the last loop in foreach?

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.


2 Answers

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 } 
like image 105
poke Avatar answered Sep 28 '22 14:09

poke


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 
like image 20
Klinky Avatar answered Sep 28 '22 14:09

Klinky