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

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

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

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

PHP中如何解决这个问题?


当前回答

你也可以这样做:

end( $elements );
$endKey = key($elements);
foreach ($elements as $key => $value)
{
     if ($key == $endKey) // -- this is the last item
     {
          // do something
     }

     // more code
}

其他回答

我个人使用这种结构,可以很容易地使用html < ul >和< li >元素:简单地更改其他属性的相等…

数组不能包含假项,只能包含转换为假布尔值的所有其他项。

$table = array( 'a' , 'b', 'c');
$it = reset($table);
while( $it !== false ) {
    echo 'all loops';echo $it;
    $nextIt = next($table);
    if ($nextIt === false || $nextIt === $it) {
            echo 'last loop or two identical items';
    }
    $it = $nextIt;
}

我有点喜欢下面的,因为我觉得它相当整洁。让我们假设我们正在创建一个字符串,所有元素之间都有分隔符:例如a,b,c

$first = true;
foreach ( $items as $item ) {
    $str = ($first)?$first=false:", ".$item;
}

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

$array = array(
    'First',
    'Second',
    'Third',
    'Last'
);

foreach($array as $key => $value)
{
    if(end($array) === $value)
    {
       echo "last index!" . $value;
    }
}

More easy by end()函数是PHP中的一个内置函数,用于查找给定数组的最后一个元素。函数的作用是:将数组的内部指针更改为指向最后一个元素,并返回最后一个元素的值。

下面是一个非整型索引的例子:

<?php
    $arr = array(
            'first' => 
                array('id' => 1, 'label' => 'one'), 
            'second' => 
                array('id' => 2, 'label' => 'two'), 
            'last' => 
                array('id' => 9, 'label' => 'nine')
        );
    $lastIndexArr = end($arr);
    print_r($lastIndexArr);

检查这里的最后一个数组作为输出。

我有一种强烈的感觉,在这个“XY问题”的根源上,OP想要的只是implode()函数。