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

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

    For SQL query generating scripts, or anything that does a different action for the first or last elements, it is much faster (almost twice as fast) to avoid using unneccessary variable checks.

    The current accepted solution uses a loop and a check within the loop that will be made every_single_iteration, the correct (fast) way to do this is the following :

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

    A little homemade benchmark showed the following:

    test1: 100000 runs of model morg

    time: 1869.3430423737 milliseconds

    test2: 100000 runs of model if last

    time: 3235.6359958649 milliseconds

    And it's thus quite clear that the check costs a lot, and of course it gets even worse the more variable checks you add ;)

提交回复
热议问题