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

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

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

我相信一定有某种标准的方法来做这件事。

PHP中如何解决这个问题?


当前回答

试试这个简单的解决方案

$test = ['a' => 1, 'b' => 2, 'c' => 3];

$last_array_value = end($test);

foreach ($test as $key => $value) {
   if ($value === $last_array_value) {
      echo $value; // display the last value  
   } else {
     echo $value; // display the values that are not last elements 
   }
}

其他回答

这里有另一种方法:

$arr = range(1, 10);

$end = end($arr);
reset($arr);

while( list($k, $v) = each($arr) )
{
    if( $n == $end )
    {
        echo 'last!';
    }
    else
    {
        echo sprintf('%s ', $v);
    }
}

听起来你想要的是这样的:

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

也就是说,你不必在php中使用foreach遍历一个“数组”。

已经有很多答案了,但也有必要研究一下迭代器,特别是当它被要求使用标准方式时:

$arr = range(1, 3);

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

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

如果它是一个一维数组,你可以这样做,以保持它的简短和甜蜜:

foreach($items as $idx => $item) {
    if (!isset($items[$idx+1])) {
        print "I am last";
    }
}

你可以直接得到最后一个索引:

$numItems = 计数($arr);

echo $ giba [numItems-1美元];