Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the key of the only element in a PHP array

The key of the associative array is dynamically generated. How do I get the "Key" of such an array?

$arr = array ('dynamic_key' => 'Value');

I am aware that It is possible to access it through a foreach loop like this:

foreach ($arr as $key => $val) echo "Key value is $key";

However, I know that this array will have only one key and want to avoid a foreach loop. Is it possible to access the value of this element in any other way? Or get the key name?

like image 402
shxfee Avatar asked Feb 16 '10 07:02

shxfee


People also ask

How do I get only the key of an array?

array_keys() returns the keys, numeric and string, from the array . If a search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.

How do you print the key of an array in PHP?

Print Array Keys With foreach and array_keys in PHPDuring the loop, we call array_keys on the array, which will extract the keys from the array. We can pass the keys to a variable in the foreach loop. Afterward, we extract the keys with foreach and array_keys .

How get the key of an object in PHP?

To display only the keys from an object, use array_keys() in PHP.

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.


1 Answers

edit: http://php.net/each says:

each

Warning This function has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.


Using key() is fine.
If you're going to fetch the value anyway you can also use each() and list().

$arr = array ('dynamic_key' => 'Value');
list($key, $value) = each($arr);
echo $key, ' -> ', $value, "\n";

prints dynamic_key -> Value

like image 193
VolkerK Avatar answered Sep 20 '22 18:09

VolkerK