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

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

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

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

PHP中如何解决这个问题?


当前回答

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

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

其他回答

<?php foreach($have_comments as $key => $page_comment): ?>
    <?php echo $page_comment;?>
    <?php if($key+1<count($have_comments)): ?> 
        <?php echo ', '; ?>
    <?php endif;?>
<?php endforeach;?>

试试这个简单的解决方案

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

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

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

用"end"怎么样? http://php.net/manual/en/function.end.php

你可以使用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
    }
}