Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the final key of an array in PHP

Tags:

arrays

php

I have a standard associative array in PHP. what's the simplest way to get the last key in that array?

example:

$foo = array('key1' => 'val1', 'key2' => 'val2', 'key3' => 'val3');

and i would like to get 'key3';

like image 539
GSto Avatar asked Jun 11 '10 17:06

GSto


People also ask

Is last key array PHP?

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.

What is Array_keys () used for in PHP?

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.

How do you print the last element of an array in PHP?

The end() function moves the internal pointer to, and outputs, the last element in the array. Related methods: current() - returns the value of the current element in an array.

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.


2 Answers

Fastest method would be this:

end($foo);
$last = key($foo);

Tesserex's method is unnecessarily resource hungry when you don't need all keys.

like image 55
Emil Vikström Avatar answered Oct 13 '22 09:10

Emil Vikström


$keys = array_keys($foo);
$last = end($keys);

you need to pass an actual variable to end, you can't put another function inside there.

like image 33
Tesserex Avatar answered Oct 13 '22 07:10

Tesserex