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

后端 未结 8 2027
迷失自我
迷失自我 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:08

    I know this is old, and using SPL iterator maybe just an overkill, but anyway, another solution here:

    $ary = array(1, 2, 3, 4, 'last');
    $ary = new ArrayIterator($ary);
    $ary = new CachingIterator($ary);
    foreach ($ary as $each) {
        if (!$ary->hasNext()) { // we chain ArrayIterator and CachingIterator
                                // just to use this `hasNext()` method to see
                                // if this is the last element
           echo $each;
        }
    }
    

提交回复
热议问题