PHP - Grab the first element using a foreach

后端 未结 8 944
面向向阳花
面向向阳花 2020-12-14 07:11

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 b

相关标签:
8条回答
  • 2020-12-14 07:59

    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
    
    0 讨论(0)
  • 2020-12-14 08:03

    hm

    <?php
    $i = 0;
    foreach($ar as $sth) {
        if($i++ == 0) {
            // do something
        }
        // do something else
    }
    

    more elegant.

    0 讨论(0)
提交回复
热议问题