PHP : How to skip last element in foreach loop [du

2020-06-03 03:51发布

I have an array of objects, any array in php. How do i skip the last element in the foreach iteration?

5条回答
我命由我不由天
2楼-- · 2020-06-03 04:34

There's various ways to do this.

If your array is a sequentially zero-indexed array, you could do:

for( $i = 0, $ilen = count( $array ) - 1; $i < $ilen; $i++ )
{
    $value = $array[ $i ];

    /* do something with $value */
}

If your array is an associative array, or otherwise not sequentially zero-indexed, you could do:

$i = 0;
$ilen = count( $array );
foreach( $array as $key => $value )
{
    if( ++$i == $ilen ) break;

    /* do something with $value */
}
查看更多
够拽才男人
3楼-- · 2020-06-03 04:37

Use a variable to track how many elements have been iterated so far and cut the loop when it reaches the end:

$count = count($array);

foreach ($array as $key => $val) {
    if (--$count <= 0) {
        break;
    }

    echo "$key = $val\n";
}

If you don't care about memory, you can iterate over a shortened copy of the array:

foreach (array_slice($array, 0, count($array) - 1) as $key => $val) {
    echo "$key = $val\n";
}
查看更多
仙女界的扛把子
4楼-- · 2020-06-03 04:38

If you don't want to delete the last array entry with pop, you could skip it like this

$array = array('v1','v2','v3',...)

$counter = 1;

foreach($array as $value)
{
    //do your thing in loop

    if($counter == count($array)) continue; // this will skip to next iteration if last element encountered.
    $counter++;
}
查看更多
地球回转人心会变
5楼-- · 2020-06-03 04:41

What you are trying to do will defeat the purpose of foreach loop. It is meant to loop through the entire array and make our job easy.

for ex: You can get the array size using COUNT function in php and then can use for loop and set the limit to arraysize-2, so the last array will be omitted

查看更多
欢心
6楼-- · 2020-06-03 04:43
$count = count($array);
$i=0;
foreach ($arr as &$value) 
{
    $i++;
    if($i==($count-1))
    {
      echo 'skip';
    }
    else
    {
      echo $value;
    }
}
查看更多
登录 后发表回答