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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6092054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:20:04  来源:igfitidea点击:

Checking during array iteration, if the current element is the last element

phparrays

提问by shealtiel

Please help me to translate this pseudo-code to real php code:

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

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

Edit: the array may have numerical or string keys

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

回答by Ibrahim Azhar Armar

you can use PHP's end()

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

更新1

as pointed out by @Mijoja the above could will have problem if you have same value multiple times in array. below is the fix for it.

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

更新2

I found solution by @onteria_ to be better then what i have answered since it does not modify arrays internal pointer, i am updating the answer to match his answer.

我发现@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.
    }
}

Thank you @onteria_

谢谢@onteria_

Update3

更新3

As pointed by @CGundlach PHP 7.3 introduced array_key_lastwhich seems much better option if you are using PHP >= 7.3

正如@CGundlach PHP 7.3 所指出的,array_key_last如果您使用的是 PHP >= 7.3,这似乎是更好的选择

$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'; 
    }
}

回答by Richard Merchant

This always does the trick for me

这总是对我有用

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

Edit 30/04/15

编辑 30/04/15

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

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

To avoid the E_STRICT warning mentioned by @Warren Sergent

为了避免@Warren Sergent 提到的 E_STRICT 警告

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

回答by onteria_

$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";
  }
}

Since array_popworks on the temporary array created by array_keysit doesn't modify the original array at all.

由于对它array_pop创建的临时数组起作用,array_keys它根本不会修改原始数组。

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

回答by PreciousFocus

Why not this very simple method:

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

$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
    }
}

回答by unifreak

I know this is old, and using SPL iterator maybe just an overkill, but anyway, another solution here:

我知道这是旧的,使用 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;
    }
}

回答by Edwin Wong

My solution, also quite simple..

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

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

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

回答by trusktr

If the items are numerically ordered, use the key() function to determine the index of the current item and compare it to the length. You'd have to use next() or prev() to cycle through items in a while loop instead of a for loop:

如果项目按数字排序,则使用 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
}

回答by Luca Filosofi

$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