15

Hay, i have an array which contains a set of arrays, here's an example.

array(
    [0]=>array('name'=>'bob'),
    [2]=>array('name'=>'tom'),
    [3]=array('name'=>'mark')
)

How would i get the last item in the array, and returns it's key.

So in the above example it would return 3.

dotty
  • 40,405
  • 66
  • 150
  • 195

5 Answers5

33
end($array);
echo key($array)

This should return the key of the last element.

cem
  • 3,311
  • 1
  • 18
  • 23
14

Try $lastKey = end(array_keys($array));

Dunhamzzz
  • 14,682
  • 4
  • 50
  • 74
  • @yes123 And? It still works, and it's all in one line which is nice. – Dunhamzzz Jun 06 '11 at 11:34
  • 15
    I don't want to be overly pedantic, but this will give a `Strict Standards: Only variables should be passed by reference ...` message. – Yoshi Jun 06 '11 at 11:35
4
<?php
$a = array(
    0=>array('name'=>'bob'),
    2=>array('name'=>'tom'),
    3=>array('name'=>'mark')
);


$b = array_keys($a);
echo end($b);

?>

something like this

kskaradzinski
  • 4,954
  • 10
  • 48
  • 70
3

Another option:

$last_key = key(array_slice($array, -1, true));
Alix Axel
  • 151,645
  • 95
  • 393
  • 500
0

You can create function and use it:

function endKey($array){
end($array);
return key($array);
}

$array = array("one" => "apple", "two" => "orange", "three" => "pear");
echo endKey($array);
Atif Tariq
  • 2,650
  • 27
  • 34