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

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

    1: Why not use a simple for statement? Assuming you're using a real array and not an Iterator you could easily check whether the counter variable is 0 or one less than the whole number of elements. In my opinion this is the most clean and understandable solution...

    $array = array( ... );
    
    $count = count( $array );
    
    for ( $i = 0; $i < $count; $i++ )
    {
    
        $current = $array[ $i ];
    
        if ( $i == 0 )
        {
    
            // process first element
    
        }
    
        if ( $i == $count - 1 )
        {
    
            // process last element
    
        }
    
    }
    

    2: You should consider using Nested Sets to store your tree structure. Additionally you can improve the whole thing by using recursive functions.

提交回复
热议问题