Peter
Peter

Reputation: 9123

Finding the first, last and nth row in a foreach loop

I was wondering if PHP has a gracefull method to find the first, last and/or nth row in a foreach loop.

I could do it using a counter as follows:

$i = 0;
$last = count($array)-1;
foreach ($array as $key => $row) {
    if ($i == 0) {
        // First row
    }

    if ($i == $last) {
        // Last row
    }
    $i++;
}

But somehow this feels like a bit of a dirty fix. Any solutions or suggestions?

Edit

As suggested in the comments I moved the count($array) outside the loop.

Upvotes: 1

Views: 2289

Answers (4)

developerjack
developerjack

Reputation: 1223

Using Arrays

For the first element in an array you can simply seek $array[0];. Depending on the array cursor you can also use current($array);

For the middle of an array you can use a combination of array_search() and array_keys().

For the end of an array you can use end($array); noting that this aslso moves the array cursor to the last element as well (as opposed to simply returning the value).

Using Iterators

However ArrayIterator's may also work well in your case:

The first element is available at ArrayIterator::current(); once constructed. (If you're halfway through the iterator you'll need to reset().)

For the n'th or a middle element you can use an undocumented Iterator::seek($index); method.

For the last element you can use a combination of seek() and count().

For example:

$array = array('frank' => 'one',
               'susan' => 'two',
               'ahmed' => 'three');

$arrayobject = new ArrayObject($array);
$iterator = $arrayobject->getIterator();

// First:
echo $iterator->current() . PHP_EOL;

// n'th:   (taken from the documentation)
if($iterator->valid()){
    $iterator->seek(1);            // expected: two, output: two
    echo $iterator->current() . PHP_EOL;    // two
}

// last: 
$iterator->seek(count($iterator)-1);
echo $iterator->current() . PHP_EOL;

Upvotes: 1

Monty Khanna
Monty Khanna

Reputation: 1120

In php we have current and end function to get first and last value of array.

<?php
$transport = array('foot', 'bike', 'car', 'plane');
echo $first = current($transport); // 'foot';
echo $end = end($transport); // 'plane';
?>

Modified :

Easy way without using current or end or foreach loop:

$last = count($transport) - 1;
echo "First : $transport[0]";
echo "</br>";
echo "Last : $transport[$last]";

Upvotes: 1

AsgarAli
AsgarAli

Reputation: 2211

$arr = ["A", "B", "C", "D", "E"];
reset($arr);
// Get First Value From Array
echo current($arr);
// Get Last Value From Array 
echo end($arr);

Visit below link for details of above used functions.

reset() : http://php.net/manual/en/function.reset.php

current() : http://php.net/manual/en/function.current.php

end() : http://php.net/manual/en/function.end.php

Upvotes: 0

Yusup Bugacheev
Yusup Bugacheev

Reputation: 511

foreach ($array as $key => $row) {

        $index = array_search($key, array_keys($array));

        if ($index  ==  0) {
            // First row
        }

        if ($index  ==  count($array) - 1) {
            // Last row
        }
    }

Upvotes: 1

Related Questions