[php] Checking during array iteration, if the current element is the last element

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)
        doSomething();

Edit: the array may have numerical or string keys

This question is related to php arrays

The answer is


Why not this very simple method:

$i = 0; //a counter to track which element we are at
foreach($array as $index => $value) {
    $i++;
    if( $i == sizeof($array) ){
        //we are at the last element of the array
    }
}

$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

$myarray = array(
  'test1' => 'foo',
  'test2' => 'bar',
  'test3' => 'baz',
  'test4' => 'waldo'
);

$myarray2 = array(
'foo',
'bar',
'baz',
'waldo'
);

// Get the last array_key
$last = array_pop(array_keys($myarray));
foreach($myarray as $key => $value) {
  if($key != $last) {
    echo "$key -> $value\n";
  }
}

// Get the last array_key
$last = array_pop(array_keys($myarray2));
foreach($myarray2 as $key => $value) {
  if($key != $last) {
    echo "$key -> $value\n";
  }
}

Since array_pop works on the temporary array created by array_keys it doesn't modify the original array at all.

$ php test.php
test1 -> foo
test2 -> bar
test3 -> baz
0 -> foo
1 -> bar
2 -> baz

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;
    }
}

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
}

My solution, also quite simple..

$array = [...];
$last = count($array) - 1;

foreach($array as $index => $value) 
{
     if($index == $last)
        // this is last array
     else
        // this is not last array
}

This always does the trick for me

foreach($array as $key => $value) {
   if (end(array_keys($array)) == $key)
       // Last key reached
}

Edit 30/04/15

$last_key = end(array_keys($array));
reset($array);

foreach($array as $key => $value) {
  if ( $key == $last_key)
      // Last key reached
}

To avoid the E_STRICT warning mentioned by @Warren Sergent

$array_keys = array_keys($array);
$last_key = end($array_keys);