How to determine the first and last iteration in a foreach loop?

前端 未结 20 1117
遇见更好的自我
遇见更好的自我 2020-11-22 16:45

The question is simple. I have a foreach loop in my code:

foreach($array as $element) {
    //code
}

In this loop, I want to r

相关标签:
20条回答
  • 2020-11-22 17:35

    Best answer:

    $arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    
    foreach ($arr as $a) {
    
    // This is the line that does the checking
    if (!each($arr)) echo "End!\n";
    
    echo $a."\n";
    
    }
    
    0 讨论(0)
  • 2020-11-22 17:36

    With Keys and Values this works as well:

    foreach ($array as $key => $value) {
        if ($value === end($array)) {
            echo "LAST ELEMENT!";
        }
    }
    
    0 讨论(0)
提交回复
热议问题