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

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

    Using a Boolean variable is still the most reliable, even if you want to check the first appearance of a $value (I found it more useful in my situation and in many situations), such like this:

    $is_first = true;
    
    foreach( $array as $value ) {
        switch ( $value ) {
            case 'match':
                echo 'appeared';
    
                if ( $is_first ) {
                    echo 'first appearance';
                    $is_first = false;
                }
    
                break;
            }
        }
    
        if( !next( $array ) ) {
            echo 'last value';
        }
    }
    

    Then how about !next( $array ) to find the last $value which will return true if there's no next() value to iterate.

    And I prefer to use a for loop instead of foreach if I were going to use a counter, like this:

    $len = count( $array );
    for ( $i = 0; $i < $len; $i++ ) {
        $value = $array[$i];
        if ($i === 0) {
            // first
        } elseif ( $i === $len - 1 ) {
            // last
        }
        // …
        $i++;
    }
    

提交回复
热议问题