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

2021-12-26 00:00:00 foreach php

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

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.

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

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

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

我相信一定有一些标准的方法可以做到这一点.

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

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

How do you solve this in PHP?

推荐答案

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

It sounds like you want something like this:

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

话虽如此,您不必在 php 中使用 foreach 迭代数组".

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

相关文章