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

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

    Simply this works!

    // Set the array pointer to the last key
    end($array);
    // Store the last key
    $lastkey = key($array);  
    foreach($array as $key => $element) {
        ....do array stuff
        if ($lastkey === key($array))
            echo 'THE LAST ELEMENT! '.$array[$lastkey];
    }
    

    Thank you @billynoah for your sorting out the end issue.

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

    The most efficient answer from @morg, unlike foreach, only works for proper arrays, not hash map objects. This answer avoids the overhead of a conditional statement for every iteration of the loop, as in most of these answers (including the accepted answer) by specifically handling the first and last element, and looping over the middle elements.

    The array_keys function can be used to make the efficient answer work like foreach:

    $keys = array_keys($arr);
    $numItems = count($keys);
    $i=0;
    
    $firstItem=$arr[$keys[0]];
    
    # Special handling of the first item goes here
    
    $i++;
    while($i<$numItems-1){
        $item=$arr[$keys[$i]];
        # Handling of regular items
        $i++;
    }
    
    $lastItem=$arr[$keys[$i]];
    
    # Special handling of the last item goes here
    
    $i++;
    

    I haven't done benchmarking on this, but no logic has been added to the loop, which is were the biggest hit to performance happens, so I'd suspect that the benchmarks provided with the efficient answer are pretty close.

    If you wanted to functionalize this kind of thing, I've taken a swing at such an iterateList function here. Although, you might want to benchmark the gist code if you're super concerned about efficiency. I'm not sure how much overhead all the function invocation introduces.

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

    Try this:

    function children( &$parents, $parent, $selected ){
      if ($parents[$parent]){
        $list = '<ul>';
        $counter = count($parents[$parent]);
        $class = array('first');
        foreach ($parents[$parent] as $child){
          if ($child['id'] == $selected)  $class[] = 'active';
          if (!--$counter) $class[] = 'last';
          $list .= '<li class="' . implode(' ', $class) . '"><div><a href="]?id=' . $child['id'] . '" alt="' . $child['name'] . '">' . $child['name'] . '</a></div></li>';
          $class = array();
          $list .= children($parents, $child['id'], $selected);
        }
        $list .= '</ul>';
        return $list;
      }
    }
    $output .= children( $parents, 0, $p_industry_id);
    
    0 讨论(0)
  • 2020-11-22 17:29

    You could use a counter:

    $i = 0;
    $len = count($array);
    foreach ($array as $item) {
        if ($i == 0) {
            // first
        } else if ($i == $len - 1) {
            // last
        }
        // …
        $i++;
    }
    
    0 讨论(0)
  • 2020-11-22 17:29

    To find the last item, I find this piece of code works every time:

    foreach( $items as $item ) {
        if( !next( $items ) ) {
            echo 'Last Item';
        }
    }
    
    0 讨论(0)
  • 2020-11-22 17:34

    You can use the counter and array length.

        $array = array(1,2,3,4);
    
        $i = 0;
        $len = count($array);
        foreach ($array as $item) {
            if ($i === 0) {
                // first
            } else if ($i === $len - 1) {
                // last
            }
            // …
            $i++;
        }
    
    0 讨论(0)
提交回复
热议问题