PHP

PHP – How to determine the first and last iteration in a for each loop

The question is simple. we have a for each loop in our code:

Php Code
foreach($array as $element) {
//code
}

In this loop, we want to react differently when we are in first or last iteration.

How to do this?

Php loops for each

Use a counter:

Php Code
$i = 0;
$len = count($array);
foreach ($array as $item) {
    if ($i == 0) {
        // first
    } else if ($i == $len - 1) {
        // last
    }
    // …
    $i++;
}

Another example:

Php Code
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

foreach ($arr as $a) 
{

// This is the line that does the checking
if (!each($arr)) echo "End!\n";

echo $a."\n";

}

Try this code:

Php Code
//Store the last key
$lastkey = key(end($array)); 
foreach($array as $key => $element) 
{
    ....do array stuff
    if ($lastkey === key($array))
        echo 'LAST ELEMENT!';
}

If your array has unique array values, then determining the first and last element is trivial:

Php Code
foreach($array as $element) {
    if ($element === reset($array))
        echo 'FIRST ELEMENT!';

    if ($element === end($array))
        echo 'LAST ELEMENT!';
}

This works if last and first elements are appearing just once in an array, otherwise you get false positives. Therefore, you have to compare the keys (they are unique for sure).

Php Code
foreach($array as $key => $element) 
{
    reset($array);
    if ($key === key($array))
        echo 'FIRST ELEMENT!';

    end($array);
    if ($key === key($array))
        echo 'LAST ELEMENT!';
}

Update: Some people are concerned about performance and/or modifying the array pointer inside a foreach loop.

For those, you can cache the key value before the loop.

Php Code
reset($array);
$first = key($array);
foreach($array as $key => $element) 
{
    if ($key === $first)
        echo 'FIRST ELEMENT!';
}

READ  nginx error connect to php5-fpm.sock failed (13: Permission denied)

A more simplified version of the above and presuming you’re not using custom indexes…

Php Code


$len = count($array);
foreach ($array as $index => $item) {
    if ($index == 0) {
        // first
    } else if ($index == $len - 1) {
        // last
    }
}

If you only need just the first element then you may try this code.

Php Code
$firstElement = true;

foreach ($reportData->result() as $row) 
{
       if($firstElement) { echo "first element"; $firstElement=false; }
       // Other lines of codes here
}

About the author

Wikitechy Editor

Wikitechy Editor

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

X