Q:

Find Next to Last Element in PHP Foreach

I need to write a script that returns the next-to-last element in a foreach loop. Something like the below concept. How would I go about doing so?
foreach($row as $r) {
    if (element index is last - 1) {
        echo "The next-to-last element is" . $r;
    }
}

A:

This should work for you:
Just get the keys of your array into a variable and then check if the current key of the iteration is equal to the penultimate key.
$keys = array_keys($row);
$penultimatekey = count($row)-2 >= 0 ? count($row)-2 : 0;

foreach($row as $k => $r) {
    if ($k == $keys[$penultimatekey]) {
        echo "The next-to-last element is" . $r;
    }
}

