Checking during array iteration, if the current element is the last element

后端 未结 8 2019
迷失自我
迷失自我 2020-12-13 03:41

Please help me to translate this pseudo-code to real php code:

 foreach ($arr as $k => $v)
    if ( THIS IS NOT THE LAST ELEMENT IN THE ARRAY)
        doS         


        
相关标签:
8条回答
  • 2020-12-13 04:10

    If the items are numerically ordered, use the key() function to determine the index of the current item and compare it to the length. You'd have to use next() or prev() to cycle through items in a while loop instead of a for loop:

    $length = sizeOf($arr);
    while (key(current($arr)) != $length-1) {
        $v = current($arr); doSomething($v); //do something if not the last item
        next($myArray); //set pointer to next item
    }
    
    0 讨论(0)
  • 2020-12-13 04:11
    $arr = array(1, 'a', 3, 4 => 1, 'b' => 1);
    foreach ($arr as $key => $val) {
        echo "{$key} = {$val}" . (end(array_keys($arr))===$key ? '' : ', ');
    }
    // output: 0 = 1, 1 = a, 2 = 3, 4 = 1, b = 1
    
    0 讨论(0)
提交回复
热议问题