Paolo Rossi
Paolo Rossi

Reputation: 2510

Find last value of array in foreach cicle

I've data stored in a array ($rows). For read the array and genarate a dinamic table I use foreach function.

<table>

    foreach ($rows as $row) {
        echo "<tr>";
        echo "<td>" . $row['field1'] . "</td>";
        echo "<td>" . $row['field2'] . "</td>";
        echo "<td>" . $row['filed3'] . "</td>";
        echo "</tr>"; 
    }

</table>

My goal is to find the last value of the array (the end) in order to change the class of TR element for the last line displayed. How could I do this? Thanks

Upvotes: 0

Views: 132

Answers (4)

dfsq
dfsq

Reputation: 193261

Try this:

foreach ($rows as $key => $row) {
    $end = end($rows) === $row ? 'class="last"' : '';
    echo "<tr $end>";
    echo "<td>" . $row['field1'] . "</td>";
    echo "<td>" . $row['field2'] . "</td>";
    echo "<td>" . $row['filed3'] . "</td>";
    echo "</tr>"; 
}

This method works for multidimentional arrays as well.

http://codepad.org/HQG9ytBX

Edit. As pointed in comments, this approach may potentially trigger false end result if some values in the array are duplicated (with the last). Correct bullet-proof version should be:

foreach ($rows as $key => $row) {
    $end = end($rows) === $row && $key === key($rows) ? 'class="last"' : '';

    // ...

Upvotes: 1

Your Common Sense
Your Common Sense

Reputation: 157839

// first, let's find out the last key
end($rows);
$last = key($rows);

// then just loop over
foreach ($rows as $key => $row) {
        if ($key == $last) {
            // last leaf of the summer...
        }
        echo "<tr>";
        echo "<td>" . $row['field1'] . "</td>";
        echo "<td>" . $row['field2'] . "</td>";
        echo "<td>" . $row['filed3'] . "</td>";
        echo "</tr>"; 
}

Upvotes: 0

alwaysLearn
alwaysLearn

Reputation: 6950

Try This

$numItems = count($rows);
$i = 0;
foreach($rows as $row) {

$trClass = 'firstclass';
if(++$i === $numItems) 
{
$trClass = 'lastclass';
}


echo "<tr class='$trclass'>";
    echo "<td>" . $row['field1'] . "</td>";
    echo "<td>" . $row['field2'] . "</td>";
    echo "<td>" . $row['filed3'] . "</td>";
    echo "</tr>"; 
}  

Upvotes: 0

M. Amir Ul Amin
M. Amir Ul Amin

Reputation: 81

foreach ($rows as $row) {
$is_last_row = ++$i == count($rows);
        echo "<tr>";
        echo "<td>" . $row['field1'] . "</td>";
        echo "<td>" . $row['field2'] . "</td>";
        echo "<td>" . $row['filed3'] . "</td>";
        echo "</tr>"; 
    }

here $i should be an unused variable.

Upvotes: 1

Related Questions