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

前端 未结 20 1122
遇见更好的自我
遇见更好的自我 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:27

    Simply this works!

    // Set the array pointer to the last key
    end($array);
    // Store the last key
    $lastkey = key($array);  
    foreach($array as $key => $element) {
        ....do array stuff
        if ($lastkey === key($array))
            echo 'THE LAST ELEMENT! '.$array[$lastkey];
    }
    

    Thank you @billynoah for your sorting out the end issue.

提交回复
热议问题