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

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

    If you prefer a solution that does not require the initialization of the counter outside the loop, I propose comparing the current iteration key against the function that tells you the last / first key of the array.

    This becomes somewhat more efficient (and more readable) with the upcoming PHP 7.3.

    Solution for PHP 7.3 and up:

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

    Solution for all PHP versions:

    foreach($array as $key => $element) {
        reset($array);
        if ($key === key($array))
            echo 'FIRST ELEMENT!';
    
        end($array);
        if ($key === key($array))
            echo 'LAST ELEMENT!';
    }
    
    0 讨论(0)
  • 2020-11-22 17:12

    I came across this thread when I have the same problem. I only need to get the first element then I re-analyze my code until this came up to my mind.

    $firstElement = true;
    
    foreach ($reportData->result() as $row) 
    {
           if($firstElement) { echo "first element"; $firstElement=false; }
           // Other lines of codes here
    }
    

    The above codes are great and complete but if you only need just the first element then you may try this code.

    0 讨论(0)
  • 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.
    0 讨论(0)
  • 2020-11-22 17:13

    An attempt to find the first would be:

    $first = true; 
    foreach ( $obj as $value )
    {
      if ( $first )
      {
        // do something
        $first = false; //in order not to get into the if statement for the next loops
      }
      else
      {
        // do something else for all loops except the first
      }
    }
    
    0 讨论(0)
  • 2020-11-22 17:16

    Using reset($array) and end($array)

    <?php
    
        $arrays = [1,2,3,4,5];
    
        $first  = reset($arrays);
        $last   = end($arrays);    
    
        foreach( $arrays as $array )
        {
    
            if ( $first == $array )
            {
                echo "<li>{$array} first</li>";
            }
            else if ( $last == $array )
            {
                echo "<li>{$array} last</li>";
            }
            else
            {
                echo "<li>{$array}</li>";
            }                
    
        }
    

    Demo repl.it

    0 讨论(0)
  • 2020-11-22 17:17

    Not sure if it still necessary. But the following solution should work with iterators and does not require count.

    <?php
    
    foreach_first_last(array(), function ($key, $value, $step, $first, $last) {
        echo intval($first), ' ', intval($last), ' ', $step, ' ', $value, PHP_EOL;
    });
    
    foreach_first_last(array('aa'), function ($key, $value, $step, $first, $last) {
        echo intval($first), ' ', intval($last), ' ', $step, ' ', $value, PHP_EOL;
    });
    echo PHP_EOL;
    
    foreach_first_last(array('aa', 'bb', 'cc'), function ($key, $value, $step, $first, $last) {
        echo intval($first), ' ', intval($last), ' ', $step, ' ', $value, PHP_EOL;
    });
    echo PHP_EOL;
    
    function foreach_first_last($array, $cb)
    {
        $next = false;
        $current = false;
        reset($array);
        for ($step = 0; true; ++$step) {
            $current = $next;
            $next = each($array);
            $last = ($next === false || $next === null);
            if ($step > 0) {
                $first = $step == 1;
                list ($key, $value) = $current;
                if (call_user_func($cb, $key, $value, $step, $first, $last) === false) {
                    break;
                }
            }
            if ($last) {
                break;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题