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

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

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

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

PHP中如何解决这个问题?


当前回答

这里有另一种方法:

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

其他回答

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

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

假设你把数组存储在一个变量中…

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

我个人使用这种结构,可以很容易地使用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;
}
$array  = array("dog", "rabbit", "horse", "rat", "cat");
foreach($array as $index => $animal) {
    if ($index === array_key_first($array))
        echo $animal; // output: dog

    if ($index === array_key_last($array))
        echo $animal; // output: cat
}

注意:这不起作用,因为调用next()会使数组指针向前移动,因此您将跳过循环中的所有其他元素


为什么这么复杂?

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

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