PHP - Grab the first element using a foreach

2020-02-08 11:09发布

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?

8条回答
爷、活的狠高调
2楼-- · 2020-02-08 11:34

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++;
}
查看更多
太酷不给撩
3楼-- · 2020-02-08 11:36
foreach($array as $element) {
    if ($element === reset($array))
        echo 'FIRST ELEMENT!';

    if ($element === end($array))
        echo 'LAST ELEMENT!';
}
查看更多
老娘就宠你
4楼-- · 2020-02-08 11:39

This is also works

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

    if ($element === end($array))
        echo 'LAST ELEMENT!';
}
查看更多
Summer. ? 凉城
5楼-- · 2020-02-08 11:42

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
}
查看更多
Viruses.
6楼-- · 2020-02-08 11:43
first = true
foreach(...)
    if first
        do stuff
        first = false
查看更多
孤傲高冷的网名
7楼-- · 2020-02-08 11:47

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
查看更多
登录 后发表回答