The last record in the array returns null

Viewed 83

I am writing a PHP exercise script for the elevator and the people there, it's not important, because everything is ready, though - there was a problem at the end of the task. I want to display the last record of an array, more specifically the weight.

Sorry, I'm getting a null argument error, although print_r of the last array record returns the correct data. What am I doing wrong?

$elevatorContent = array (

    array (
    "firstname" => "Peter",
    "weight" => 70
    ),

    array (
    "firstname" => "Cassie",
    "weight" => 70
    ),

    array (
    "firstname" => "John",
    "weight" => 150
    ),

    array (
    "firstname" => "Agnes",
    "weight" => 150
    ),

);  

This returns null

echo "<p>The last person in elevator is <b>".end($elevatorContent['firstname']). "<b></p>";
4 Answers

You need small correction :

php end() returns last element of given array, so you have to get last element first, and then access it by your key.

Since PHP 5.4 :

From

end($elevatorContent['firstname'])

To

echo end($elevatorContent)["firstname"];

OR

On PHP 5.3 or earlier, you'll need to use a temporary variable.

$last_arr = end($elevatorContent);
echo $last_arr["firstname"];

So it becomes:

echo "<p>The last person in elevator is <b>" . end($elevatorContent)['firstname'] . "<b></p>";

OR

$last_arr = end($elevatorContent);
echo "<p>The last person in elevator is <b>".$last_arr["firstname"]. "<b></p>";
echo "<p>The last person in elevator is <b>" . end($elevatorContent)['firstname'] . "<b></p>";

Try:

echo "<p>The last person in elevator is <b>" . $elevatorContent[count($elevatorContent) - 1]['firstname'] . "<b></p>";
$last = end($elevatorContent);
echo "<p>The last person in elevator is <b>".$last['firstname']. "<b></p>";
Related