在数组迭代期间检查,如果当前元素是最后一个元素

时间:2011-05-23 01:42:49

标签: php arrays

请帮我把这个伪代码翻译成真正的PHP代码:

 foreach ($arr as $k => $v)
    if ( THIS IS NOT THE LAST ELEMENT IN THE ARRAY)
        doSomething();

编辑:数组可能包含数字或字符串键

10 个答案:

答案 0 :(得分:111)

您可以使用PHP的end()

$array = array('a' => 1,'b' => 2,'c' => 3);
$lastElement = end($array);
foreach($array as $k => $v) {
    echo $v . '<br/>';
    if($v == $lastElement) {
         // 'you can do something here as this condition states it just entered last element of an array'; 
    }
}

<强> UPDATE1

正如@Mijoja所指出的,如果你在数组中多次使用相同的值,那么上面可能会有问题。下面是它的修复。

$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 2);
//point to end of the array
end($array);
//fetch key of the last element of the array.
$lastElementKey = key($array);
//iterate the array
foreach($array as $k => $v) {
    if($k == $lastElementKey) {
        //during array iteration this condition states the last element.
    }
}

<强> UPDATE2

我发现@onteria_的解决方案比我回答的更好,因为它没有修改数组内部指针,我正在更新答案以匹配他的答案。

$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 2);
// Get array keys
$arrayKeys = array_keys($array);
// Fetch last array key
$lastArrayKey = array_pop($arrayKeys);
//iterate array
foreach($array as $k => $v) {
    if($k == $lastArrayKey) {
        //during array iteration this condition states the last element.
    }
}

谢谢@onteria _

答案 1 :(得分:19)

这对我来说总是有把戏

foreach($array as $key => $value) {
   if (end(array_keys($array)) == $key)
       // Last key reached
}

编辑30/04/15

$last_key = end(array_keys($array));
reset($array);

foreach($array as $key => $value) {
  if ( $key == $last_key)
      // Last key reached
}

避免@Warren Sergent提到的E_STRICT警告

$array_keys = array_keys($array);
$last_key = end($array_keys);

答案 2 :(得分:12)

$myarray = array(
  'test1' => 'foo',
  'test2' => 'bar',
  'test3' => 'baz',
  'test4' => 'waldo'
);

$myarray2 = array(
'foo',
'bar',
'baz',
'waldo'
);

// Get the last array_key
$last = array_pop(array_keys($myarray));
foreach($myarray as $key => $value) {
  if($key != $last) {
    echo "$key -> $value\n";
  }
}

// Get the last array_key
$last = array_pop(array_keys($myarray2));
foreach($myarray2 as $key => $value) {
  if($key != $last) {
    echo "$key -> $value\n";
  }
}

由于array_pop适用于array_keys创建的临时数组,因此根本不会修改原始数组。

$ php test.php
test1 -> foo
test2 -> bar
test3 -> baz
0 -> foo
1 -> bar
2 -> baz

答案 3 :(得分:4)

为什么不是这个非常简单的方法:

$i = 0; //a counter to track which element we are at
foreach($array as $index => $value) {
    $i++;
    if( $i == sizeof($array) ){
        //we are at the last element of the array
    }
}

答案 4 :(得分:2)

我知道这是旧的,使用SPL迭代器可能只是一种矫枉过正,但无论如何,这里有另一种解决方案:

$ary = array(1, 2, 3, 4, 'last');
$ary = new ArrayIterator($ary);
$ary = new CachingIterator($ary);
foreach ($ary as $each) {
    if (!$ary->hasNext()) { // we chain ArrayIterator and CachingIterator
                            // just to use this `hasNext()` method to see
                            // if this is the last element
       echo $each;
    }
}

答案 5 :(得分:1)

我的解决方案,也很简单..

$array = [...];
$last = count($array) - 1;

foreach($array as $index => $value) 
{
     if($index == $last)
        // this is last array
     else
        // this is not last array
}

答案 6 :(得分:0)

如果项目按数字顺序排序,请使用key()函数确定当前项目的索引并将其与长度进行比较。你必须使用next()或prev()循环while循环中的项而不是for循环:

$length = sizeOf($arr);
while (key(current($arr)) != $length-1) {
    $v = current($arr); doSomething($v); //do something if not the last item
    next($myArray); //set pointer to next item
}

答案 7 :(得分:0)

$arr = array(1, 'a', 3, 4 => 1, 'b' => 1);
foreach ($arr as $key => $val) {
    echo "{$key} = {$val}" . (end(array_keys($arr))===$key ? '' : ', ');
}
// output: 0 = 1, 1 = a, 2 = 3, 4 = 1, b = 1

答案 8 :(得分:0)

成功了

$lastKey = array_key_last($array);
foreach($array as $k => $v) {
    echo $v . '<br/>';
    if($k == $lastKey) {
         // 'you can do something here as this condition states it just entered last element of an array'; 
    }
}

答案 9 :(得分:0)

使用 array_keys 函数获取键的简单方法,并且仅获取反向数组的第一个[0],即最后一个键。< /p>

$array = array('a' => 1,'b' => 2,'c' => 3);
$last_key = array_keys(array_reverse($array, true))[0];
foreach($array as $key => $value) {
   if ($last_key !== $key)
       // THIS IS NOT THE LAST ELEMENT IN THE ARRAY doSomething();
}

注意array_reverse 反向数组采用两个参数,第一个数组我们想要颠倒,第二个参数为真,以反转数组并保留键的顺序 .