PHP get last element in array 

Joined:
03/10/2011
Posts:
84

April 10, 2011 15:00:16    Last update: April 10, 2011 15:01:25
In PHP, arrays are associative arrays (maps). As such, the elements in an array are supposedly not ordered. But they are. PHP provides the function end to let you peek at the last element of an array, and array_pop to pop the last element.

So how are the elements ordered? By the order they are added to the array, not by the index!
<?php
$fruits = array('orange', 'banana', 'apple');
$veggie[2] = 'carrot';
$veggie[1] = 'collard';
$veggie[0] = 'pea';

echo end($fruits), "\n";
echo end($veggie), "\n";

echo var_dump($fruits);
echo var_dump($veggie);

// pops 'pea', with index 0
echo array_pop($veggie), "\n";
echo var_dump($veggie);
?>

Outputs:
apple
pea
array(3) {
  [0]=>
  string(6) "orange"
  [1]=>
  string(6) "banana"
  [2]=>
  string(5) "apple"
}
array(3) {
  [2]=>
  string(6) "carrot"
  [1]=>
  string(7) "collard"
  [0]=>
  string(3) "pea"
}
pea
array(2) {
  [2]=>
  string(6) "carrot"
  [1]=>
  string(7) "collard"
}
Share |
| Comment  | Tags