PHP – How to get the element before the last element from an array?

This will work even on this array:

$array[0] = "hello";
$array[5] = "how";
$array[9] = "are";

end($array);
echo prev($array); // will print "how"

The other solutions using count() are assuming that the indexes of your array go in order; by using end and prev to move the array pointer, you get the actual values. Try using the count() method on the array above and it will fail.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)