Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get key of the last element in an array

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.

like image 925
dotty Avatar asked Jun 06 '11 11:06

dotty


People also ask

How do I get the last key of an array?

You can use the end() function in PHP to get the last element of any PHP array. It will set the internal pointer to the last element of the array and return its value.

Is last key array PHP?

The array_key_last () function in PHP gets the last key of an array if the specified array is not empty. array(required)- This parameter signifies the input array. This function returns the last key of the specified array if the array is not empty else it returns NULL.

How do you find array keys?

The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned. Specified array.

How do you find the last and first element in an array?

To get the first and last elements of an array, access the array at index 0 and the last index. For example, arr[0] returns the first element, whereas arr[arr. length - 1] returns the last element of the array.


4 Answers

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

This should return the key of the last element.

like image 127
cem Avatar answered Oct 06 '22 01:10

cem


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

like image 25
Dunhamzzz Avatar answered Oct 06 '22 00:10

Dunhamzzz


<?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

like image 20
kskaradzinski Avatar answered Oct 06 '22 02:10

kskaradzinski


Another option:

$last_key = key(array_slice($array, -1, true));
like image 29
Alix Axel Avatar answered Oct 06 '22 00:10

Alix Axel