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.
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.
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.
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.
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.
end($array);
echo key($array)
This should return the key of the last element.
Try $lastKey = end(array_keys($array));
<?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
Another option:
$last_key = key(array_slice($array, -1, true));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With