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

2022-08-30 08:07:47

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

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

编辑:数组可能具有数字或字符串键


答案 1

你可以使用 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'; 
    }
}

更新1

正如@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.
    }
}

更新2

我找到了解决方案,@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_

更新3

正如@CGundlach PHP 7.3引入的那样,如果您使用的是PHP,这似乎是更好的选择 > = 7.3array_key_last

$array = array('a' => 1,'b' => 2,'c' => 3);
$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'; 
    }
}

答案 2

这总是为我解决问题

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);