首页 文章

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

提问于
浏览
179

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

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

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

我相信必须有一些标准的方法来做到这一点 .

你如何用PHP解决这个问题?

30 回答

  • -3

    一种方法是检测迭代器是否有 next . 如果没有下一个附加到迭代器,则意味着您处于最后一个循环中 .

    foreach ($some_array as $element) {
        if(!next($some_array)) {
             // This is the last $element
        }
    }
    
  • 5

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

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

    话虽这么说,你没有 - 在php中使用 foreach 迭代"array" .

  • 37

    为什么这么复杂?

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

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

  • 0

    我个人使用这种结构,可以使用html <ul>和<li>元素轻松使用:只需更改其他属性的相等性...

    该数组不能包含false项,而是包含所有其他项,这些项都被转换为false boolean .

    $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;
    }
    
  • 0

    如果我了解你,那么你只需要反转数组并通过pop命令获取最后一个元素:

    $rev_array = array_reverse($array);
    
       echo array_pop($rev_array);
    
  • 3

    您可以使用 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
        }
    }
    
  • 4
    foreach($array as $value) {
    if ($value === end($array)) {
        echo 'LAST ITEM!';
    } }
    

    简单而真实的方式

    https://rricketts.com/php-tutorial-how-to-determine-the-first-and-last-iteration-in-a-foreach-loop/

  • 1

    您也可以尝试使用INSERT进行查询...

    <?php
     $week=array('one'=>'monday','two'=>'tuesday','three'=>'wednesday','four'=>'thursday','five'=>'friday','six'=>'saturday','seven'=>'sunday');
     $keys = array_keys($week);
     $string = "INSERT INTO my_table ('";
     $string .= implode("','", $keys);
     $string .= "') VALUES ('";
     $string .= implode("','", $week);
     $string .= "');";
     echo $string;
    ?>
    
  • 8

    您仍然可以将该方法与关联数组一起使用:

    $keys = array_keys($array);
    for ($i = 0, $l = count($array); $i < $l; ++$i) {
        $key = $array[$i];
        $value = $array[$key];
        $isLastItem = ($i == ($l - 1));
        // do stuff
    }
    
    // or this way...
    
    $i = 0;
    $l = count($array);
    foreach ($array as $key => $value) {
        $isLastItem = ($i == ($l - 1));
        // do stuff
        ++$i;
    }
    
  • 1

    因为你想要找到EOF阵列只是为了胶水 . 介绍下面的策略 . 您无需要求EOF:

    $given_array = array('column1'=>'value1',
                         'column2'=>'value2',
                         'column3'=>'value3');
    
    $glue = '';
    foreach($given_array as $column_name=>$value){
        $where .= " $glue $column_name = $value"; //appending the glue
        $glue   = 'AND';
    }
    echo $where;
    

    O / P:

    column1 = value1 AND column2 = value2 AND column3 = value3
    
  • 22

    另一种方法是记住前一个循环周期结果并将其用作最终结果:

    $result = $where = "";
        foreach ($conditions as $col => $val) {
            $result = $where .= $this->getAdapter()->quoteInto($col.' = ?', $val);
            $where .=  " AND ";
        }
        return $this->delete($result);
    
  • 267

    对于SQL查询生成脚本,或对第一个或最后一个元素执行不同操作的任何内容,它要快得多(几乎快两倍)以避免使用不必要的变量检查 .

    当前接受的解决方案在循环内使用循环和检查every_single_iteration,正确(快速)方式执行此操作如下:

    $numItems = count($arr);
    $i=0;
    $firstitem=$arr[0];
    $i++;
    while($i<$numItems-1){
        $some_item=$arr[$i];
        $i++;
    }
    $last_item=$arr[$i];
    $i++;
    

    一个小的自制基准显示如下:

    test1:模型morg的100000次运行

    时间:1869.3430423737毫秒

    test2:如果最后一次运行100000次模型

    时间:3235.6359958649毫秒

  • 20

    这是我的解决方案:只需获得数组的计数,减去1(因为它们从0开始) .

    $lastkey = count($array) - 1;
    foreach($array as $k=>$a){
        if($k==$lastkey){
            /*do something*/
        }
    }
    
  • 0

    这是你可以做到的另一种方式:

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

    我使用了一个通用的解决方案,用于从字符串值数组中编译字符串的共同目的 . 我所做的只是在末尾添加一个不寻常的字符串,然后将其替换掉 .

    Function to return a string from an array, separated, with no trailing separator:

    function returnArraySeparated($aArr, $sSep, $sAdd = "@X@") {
    
    $strReturn = (string) "";
    
    
    # Compile the set:
    foreach ($aArr as $sItem) {
        $strReturn .= $sItem . $sSep;
    }
    
    # Easy strip the end:
    $strReturn = str_replace($sSep . $sAdd, "", $strReturn . $sAdd);
    
    return $strReturn;
    }
    

    没什么特别的,但是它有效:)

  • 0

    已经有很多答案,但是也值得研究迭代器,特别是因为它被要求采用标准方法:

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

    您可能会发现某些内容对其他案例也更加灵活 .

  • 0

    你也可以这样做:

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

    我有一种强烈的感觉,在这个"XY problem"的根源上,OP只需要 implode() 功能 .

  • 1

    您可以通过以下方式直接获取最后一个索引:

    $numItems = count($arr);

    echo $arr[$numItems-1];

  • 1

    如果你需要为除第一个或最后一个元素之外的每个元素做一些事情,并且只有在数组中有多个元素时,我更喜欢以下解决方案 .

    我知道上面有很多解决方案,并在我之前发布了几个月/一年,但我认为这本身就是相当优雅的 . 检查每个循环也是一个布尔检查,而不是数字“i =(count-1)”检查,这可以减少开销 .

    循环的结构可能会感觉很尴尬,但您可以将它与HTML表格标签中的thead(开头),tfoot(结束),tbody(当前)的顺序进行比较 .

    $first = true;
    foreach($array as $key => $value) {
        if ($first) {
            $first = false;
            // Do what you want to do before the first element
            echo "List of key, value pairs:\n";
        } else {
            // Do what you want to do at the end of every element
            // except the last, assuming the list has more than one element
            echo "\n";
        }
        // Do what you want to do for the current element
        echo $key . ' => ' . $value;
    }
    

    例如,在Web开发术语中,如果要在无序列表(ul)中添加 border-bottom to every element except the last ,则可以改为添加 border-top to every element except the first (CSS:first-child,由IE7支持,Firefox / Webkit支持此逻辑,而:IE7不支持last-child) .

    您可以随意为每个嵌套循环重用$ first变量,因为每个循环在第一次迭代的第一个进程中使$ first为false,所以事情会正常工作(因此中断/异常不会导致问题) .

    $first = true;
    foreach($array as $key => $subArray) {
        if ($first) {
            $string = "List of key => value array pairs:\n";
            $first = false;
        } else {
            echo "\n";
        }
    
        $string .= $key . '=>(';
        $first = true;
        foreach($subArray as $key => $value) {
            if ($first) {
                $first = false;
            } else {
                $string .= ', ';
            }
            $string .= $key . '=>' . $value;
        }
        $string .= ')';
    }
    echo $string;
    

    输出示例:

    List of key => value array pairs:
    key1=>(v1_key1=>v1_val1, v1_key2=>v1_val2)
    key2=>(v2_key1=>v2_val1, v2_key2=>v2_val2, v2_key3=>v2_val3)
    key3=>(v3_key1=>v3_val1)
    
  • 0

    因此,如果您的数组具有唯一的数组值,那么确定上一次迭代是微不足道的:

    foreach($array as $element) {
        if ($element === end($array))
            echo 'LAST ELEMENT!';
    }
    

    如你所见,如果最后一个元素在数组中只出现一次,则可以正常工作,否则会出现误报 . 在它不是,你必须比较键(这是独一无二的) .

    foreach($array as $key => $element) {
        end($array);
        if ($key === key($array))
            echo 'LAST ELEMENT!';
    }
    

    还要注意严格的coparision运算符,这在这种情况下非常重要 .

  • 0

    你可以做一个count() .

    for ($i=0;$i<count(arr);$i++){
        $i == count(arr)-1 ? true : false;
    }
    

    或者如果您只查找最后一个元素,可以使用end() .

    end(arr);
    

    只返回最后一个元素 .

    事实证明,你可以用整数索引php数组 . 它非常满意

    arr[1];
    
  • 180
  • 1
    foreach ($array as $key => $value) {
    
      $class = ( $key !== count( $array ) -1 ) ? " class='not-last'" : " class='last'";
    
      echo "<div{$class}>";
      echo "$value['the_title']";
      echo "</div>";
    
    }
    

    Reference

  • 0

    当toEnd达到0时,表示它处于循环的最后一次迭代 .

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

    在循环之后,最后一个值仍然可用,因此如果您只想在循环之后将其用于更多内容,则更好:

    foreach($arr as $key=>$value) {
      //something
    }
    echo "last index! $key => $value";
    

    如果您不想将最后一个值视为特殊的内部循环 . 如果你有大型数组,这应该更快 . (如果在同一范围内的循环之后重用数组,则必须先“复制”该数组) .

    //If you use this in a large global code without namespaces or functions then you can copy the array like this:
    //$array = $originalArrayName; //uncomment to copy an array you may use after this loop
    
    //end($array); $lastKey = key($array); //uncomment if you use the keys
    $lastValue = array_pop($array);
    
    //do something special with the last value here before you process all the others?
    echo "Last is $lastValue", "\n";
    
    foreach ($array as $key => $value) {
        //do something with all values before the last value
        echo "All except last value: $value", "\n";
    }
    
    //do something special with the last value here after you process all the others?
    echo "Last is $lastValue", "\n";
    

    并回答你的原始问题“在我的情况下,在构建查询时附加或/和参数”;这将遍历所有值,然后将它们连接在一起,在它们之间加上“和”,但不是在第一个值之前或最后一个值之后:

    $params = [];
    foreach ($array as $value) {
        $params[] = doSomething($value);
    }
    $parameters = implode(" and ", $params);
    
  • 4

    假设您将数组存储在变量中...

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

    It sounds like you want something like this:

    $array = array(
        'First',
        'Second',
        'Third',
        'Last'
    );
    
    foreach($array as $key => $value)
    {
        if(end($array) === $value)
        {
           echo "last index!" . $value;
        }
    }
    
  • 3
    <?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;?>
    
  • 8

    这应该是找到最后一个元素的简单方法:

    foreach ( $array as $key => $a ) {
        if ( end( array_keys( $array ) ) == $key ) {
            echo "Last element";
         } else {
            echo "Just another element";
         }
    }
    

    参考:Link

  • 2

    我有点喜欢以下,因为我觉得它很整洁 . 假设我们在所有元素之间创建一个带分隔符的字符串:例如A,B,C

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

相关问题