PHP - Grab the first element using a foreach

后端 未结 8 943
面向向阳花
面向向阳花 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:45

    I saw this solution on a blog post in my search result set that brought up this post and I thought it was rather elegant. Though perhaps a bit heavy on processing.

    foreach ($array as $element) 
    {
        if ($element === reset($array))
            echo 'FIRST ELEMENT!';
    
        if ($element === end($array))
            echo 'LAST ELEMENT!';
    }
    

    Do note there is also a warning on the post that this will only work if the array values are unique. If your last element is "world" and some random element in the middle is also "world" last element will execute twice.

    0 讨论(0)
  • 2020-12-14 07:49

    You can simply add a counter to the start, like so:

    $i = 0;
    
    foreach($arr as $a){
     if($i == 0) {
     //do ze business
     }
     //the rest
     $i++;
    }
    
    0 讨论(0)
  • 2020-12-14 07:55
    first = true
    foreach(...)
        if first
            do stuff
            first = false
    
    0 讨论(0)
  • 2020-12-14 07:56

    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
    }
    
    0 讨论(0)
  • 2020-12-14 07:56
    foreach($array as $element) {
        if ($element === reset($array))
            echo 'FIRST ELEMENT!';
    
        if ($element === end($array))
            echo 'LAST ELEMENT!';
    }
    
    0 讨论(0)
  • 2020-12-14 07:58

    This is also works

    foreach($array as $element) {
        if ($element === reset($array))
            echo 'FIRST ELEMENT!';
    
        if ($element === end($array))
            echo 'LAST ELEMENT!';
    }
    
    0 讨论(0)
提交回复
热议问题