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

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

    You can use an anonymous function, too:

    $indexOfLastElement = count($array) - 1;
    array_walk($array, function($element, $index) use ($indexOfLastElement) {
        // do something
        if (0 === $index) {
            // first element‘s treatment
        }
        if ($indexOfLastElement === $index) {
            // last not least
        }
    });
    

    Three more things should be mentioned:

    • If your array isn‘t indexed strictly (numerically) you must pipe your array through array_values first.
    • If you need to modify the $element you have to pass it by reference (&$element).
    • Any variables from outside the anonymous function you need inside, you‘ll have to list them next to $indexOfLastElement inside the use construct, again by reference if needed.

提交回复
热议问题