在 PHP 中使用 foreach 循环时查找数组的最后一个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/665135/
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-24 23:25:13  来源:igfitidea点击:

Find the last element of an array while using a foreach loop in PHP

phpforeach

提问by Vaibhav Kamble

I am writing a SQL query creator using some parameters. In Java, it's very easy to detect the last element of an array from inside the for loop by just checking the current array position with the array length.

我正在使用一些参数编写 SQL 查询创建器。在 Java 中,只需通过数组长度检查当前数组位置,就可以很容易地从 for 循环内部检测数组的最后一个元素。

for(int i=0; i< arr.length;i++){
     boolean isLastElem = i== (arr.length -1) ? true : false;        
}

In PHP they have non-integer indexes to access arrays. So you must iterate over an array using a foreach loop. This becomes problematic when you need to take some decision (in my case to append or/and parameter while building query).

在 PHP 中,它们有非整数索引来访问数组。因此,您必须使用 foreach 循环遍历数组。当您需要做出一些决定(在我的情况下,在构建查询时附加或/和参数)时,这会成为问题。

I am sure there must be some standard way of doing this.

我确信必须有一些标准的方法来做到这一点。

How do you solve this in PHP?

你如何在 PHP 中解决这个问题?

回答by Richard Levasseur

It sounds like you want something like this:

听起来你想要这样的东西:

$numItems = count($arr);
$i = 0;
foreach($arr as $key=>$value) {
  if(++$i === $numItems) {
    echo "last index!";
  }
}    

That being said, you don't -have- to iterate over an "array" using foreachin php.

话虽如此,您不必-必须-foreach在 php 中使用“数组”进行迭代。

回答by Jeremy Ruten

You could get the value of the last key of the array using end(array_keys($array))and compare it to the current key:

您可以使用数组的最后一个键的值end(array_keys($array))并将其与当前键进行比较:

$last_key = end(array_keys($array));
foreach ($array as $key => $value) {
    if ($key == $last_key) {
        // last element
    } else {
        // not last element
    }
}

回答by Trikks

why so complicated?

为什么这么复杂?

foreach($input as $key => $value) {
    $ret .= "$value";
    if (next($input)==true) $ret .= ",";
}

This will add a , behind every value except the last one!

这将在除最后一个值之外的每个值后面添加一个 , !

回答by OIS

When toEnd reaches 0 it means it is at the last iteration of the loop.

当 toEnd 达到 0 时,表示它处于循环的最后一次迭代。

$toEnd = count($arr);
foreach($arr as $key=>$value) {
  if (0 === --$toEnd) {
    echo "last index! $value";
  }
}

The last value is still available after the loop, so if you just want to use it for more stuff after the loop this is better:

最后一个值在循环后仍然可用,因此如果您只想在循环后将其用于更多内容,则更好:

foreach($arr as $key=>$value) {
  //something
}
echo "last index! $key => $value";

If you do not want to treat the last value as special inside loops. This should be faster if you have large arrays. (If you reuse the array after the loop inside the same scope you have to "copy" the array first).

如果您不想将最后一个值视为特殊的内部循环。如果您有大型数组,这应该会更快。(如果在同一范围内的循环之后重用数组,则必须先“复制”数组)。

//If you use this in a large global code without namespaces or functions then you can copy the array like this:
//$array = $originalArrayName; //uncomment to copy an array you may use after this loop

//end($array); $lastKey = key($array); //uncomment if you use the keys
$lastValue = array_pop($array);

//do something special with the last value here before you process all the others?
echo "Last is $lastValue", "\n";

foreach ($array as $key => $value) {
    //do something with all values before the last value
    echo "All except last value: $value", "\n";
}

//do something special with the last value here after you process all the others?
echo "Last is $lastValue", "\n";

And to answer your original question "in my case to append or/and parameter while building query"; this will loop over all the values, then join them together to a string with " and " between them but not before the first value or after the last value:

并回答您的原始问题“在我的情况下,在构建查询时附加或/和参数”;这将遍历所有值,然后将它们连接到一个字符串中,它们之间有“和”,但不在第一个值之前或最后一个值之后:

$params = [];
foreach ($array as $value) {
    $params[] = doSomething($value);
}
$parameters = implode(" and ", $params);

回答by hakre

There are already many answers, but it's worth to look into iterators as well, especially as it has been asked for a standard way:

已经有很多答案,但也值得研究迭代器,尤其是当它被要求提供一种标准方式时:

$arr = range(1, 3);

$it = new CachingIterator(new ArrayIterator($arr));
foreach($it as $key => $value)
{
  if (!$it->hasNext()) echo 'Last:';
  echo $value, "\n";
}

You might find something that does work more flexible for other cases, too.

您可能会发现一些在其他情况下也更灵活的东西。

回答by Raheel

One way could be to detect if the iterator has next. If there is no next attached to the iterator it means you are in the last loop.

一种方法可能是检测迭代器是否具有next. 如果没有 next 附加到迭代器,则意味着您处于最后一个循环中。

foreach ($some_array as $element) {
    if(!next($some_array)) {
         // This is the last $element
    }
}

回答by Rok Kralj

So, if your array has unique array values, then determining last iteration is trivial:

因此,如果您的数组具有唯一的数组值,那么确定最后一次迭代是微不足道的:

foreach($array as $element) {
    if ($element === end($array))
        echo 'LAST ELEMENT!';
}

As you see, this works if last element is appearing just once in array, otherwise you get a false alarm. In it is not, you have to compare the keys (which are unique for sure).

如您所见,如果最后一个元素在数组中仅出现一次,则此方法有效,否则您会收到误报。事实并非如此,您必须比较密钥(肯定是唯一的)。

foreach($array as $key => $element) {
    end($array);
    if ($key === key($array))
        echo 'LAST ELEMENT!';
}

Also note the strict coparision operator, which is quite important in this case.

还要注意严格的共比运算符,这在这种情况下非常重要。

回答by Martin Heisterkamp

Assuming you have the array stored in a variable...

假设您将数组存储在变量中...

foreach($array as $key=>$value) 
{ 
    echo $value;
    if($key != count($array)-1) { echo ", "; }
}

回答by Ankit Aggarwal

If you need to do something for every element except either the first or the last and only if there is more than one element in the array, I prefer the following solution.

如果您需要对除第一个或最后一个元素之外的每个元素执行某些操作,并且仅当数组中有多个元素时,我更喜欢以下解决方案。

I know there are many solutions above and posted months/one year before mine, but this is something I feel is fairly elegant in its own right. The check every loop is also a boolean check as opposed to a numeric "i=(count-1)" check, which may allow for less overhead.

我知道上面有很多解决方案,并在我的几个月/一年之前发布,但我觉得这本身就相当优雅。检查每个循环也是一个布尔检查,而不是数字“i=(count-1)”检查,这可能会减少开销。

The structure of the loop may feel awkward, but you can compare it to the ordering of thead (beginning), tfoot (end), tbody (current) in HTML table tags.

循环的结构可能会让人感到尴尬,但您可以将其与 HTML 表格标签中的 thead(开始)、tfoot(结束)、tbody(当前)的顺序进行比较。

$first = true;
foreach($array as $key => $value) {
    if ($first) {
        $first = false;
        // Do what you want to do before the first element
        echo "List of key, value pairs:\n";
    } else {
        // Do what you want to do at the end of every element
        // except the last, assuming the list has more than one element
        echo "\n";
    }
    // Do what you want to do for the current element
    echo $key . ' => ' . $value;
}

For instance, in web development terms, if you want to add a border-bottom to every element except the lastin an unordered list (ul), then you can instead add a border-top to every element except the first(the CSS :first-child, supported by IE7+ and Firefox/Webkit supports this logic, whereas :last-child is not supported by IE7).

例如,在 Web 开发术语中,如果您想为无序列表 (ul) 中除最后一个元素之外的每个元素添加一个border-bottom,那么您可以为除第一个元素之外的每个元素添加一个border-top(CSS: IE7+ 支持的 first-child 和 Firefox/Webkit 支持此逻辑,而 :last-child 不受 IE7 支持)。

You can feel free to reuse the $first variable for each and every nested loop as well and things will work just fine since every loop makes $first false during the first process of the first iteration (so breaks/exceptions won't cause issues).

您也可以随意为每个嵌套循环重用 $first 变量,并且事情会正常工作,因为每个循环在第一次迭代的第一个过程中都使 $first 为 false(因此中断/异常不会导致问题) .

$first = true;
foreach($array as $key => $subArray) {
    if ($first) {
        $string = "List of key => value array pairs:\n";
        $first = false;
    } else {
        echo "\n";
    }

    $string .= $key . '=>(';
    $first = true;
    foreach($subArray as $key => $value) {
        if ($first) {
            $first = false;
        } else {
            $string .= ', ';
        }
        $string .= $key . '=>' . $value;
    }
    $string .= ')';
}
echo $string;

Example output:

示例输出:

List of key => value array pairs:
key1=>(v1_key1=>v1_val1, v1_key2=>v1_val2)
key2=>(v2_key1=>v2_val1, v2_key2=>v2_val2, v2_key3=>v2_val3)
key3=>(v3_key1=>v3_val1)

回答by Dulitha Kumarasiri

This should be the easy way to find the last element:

这应该是找到最后一个元素的简单方法:

foreach ( $array as $key => $a ) {
    if ( end( array_keys( $array ) ) == $key ) {
        echo "Last element";
     } else {
        echo "Just another element";
     }
}  

Reference : Link

参考:链接