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.

3
  • what about count($array); ^^ Commented Jun 6, 2011 at 11:34
  • @yes123 this won't work if the keys are numerical and in exact order, without any missing. Commented Jun 6, 2011 at 11:38
  • 2
    possible duplicate of How to get last key in an array? Commented Nov 17, 2011 at 9:30

5 Answers 5

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

This should return the key of the last element.

Sign up to request clarification or add additional context in comments.

1 Comment

in this solution the pointer of the array is modified to the last position of the array
14

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

2 Comments

@yes123 And? It still works, and it's all in one line which is nice.
I don't want to be overly pedantic, but this will give a Strict Standards: Only variables should be passed by reference ... message.
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

Comments

3

Another option:

$last_key = key(array_slice($array, -1, true));

1 Comment

This won't preserve keys, which is probably a requirement here.
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.