Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP : How to skip last element in foreach loop [duplicate]

Tags:

loops

foreach

php

I have an array of objects, any array in php. How do i skip the last element in the foreach iteration?

like image 498
muffin Avatar asked Feb 20 '14 06:02

muffin


2 Answers

Use a variable to track how many elements have been iterated so far and cut the loop when it reaches the end:

$count = count($array);

foreach ($array as $key => $val) {
    if (--$count <= 0) {
        break;
    }

    echo "$key = $val\n";
}

If you don't care about memory, you can iterate over a shortened copy of the array:

foreach (array_slice($array, 0, count($array) - 1) as $key => $val) {
    echo "$key = $val\n";
}
like image 77
Ja͢ck Avatar answered Sep 20 '22 17:09

Ja͢ck


There's various ways to do this.

If your array is a sequentially zero-indexed array, you could do:

for( $i = 0, $ilen = count( $array ) - 1; $i < $ilen; $i++ )
{
    $value = $array[ $i ];

    /* do something with $value */
}

If your array is an associative array, or otherwise not sequentially zero-indexed, you could do:

$i = 0;
$ilen = count( $array );
foreach( $array as $key => $value )
{
    if( ++$i == $ilen ) break;

    /* do something with $value */
}
like image 38
Decent Dabbler Avatar answered Sep 19 '22 17:09

Decent Dabbler