Getting the key of the only element in a PHP array

只愿长相守 提交于 2020-01-11 08:14:09

问题


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?


回答1:


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




回答2:


$keys = array_keys($arr);
echo $keys[0];

Or use array_values() for the value.




回答3:


Shortest, easiest and most independent solution is:

$key   = key($arr);
$value = reset($arr);



回答4:


You can use array_shift(array_keys($arr)) (with array_values for getting the value), but it still does a loop internally.




回答5:


What about array_keys()?

It does return an array though...




回答6:


do you mean that you have the value of entry and want to get the key ?

array_search ($value, $array) 

Returns the key for needle if it is found in the array, FALSE otherwise.

If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.

more details : http://php.net/manual/en/function.array-search.php



来源:https://stackoverflow.com/questions/2271129/getting-the-key-of-the-only-element-in-a-php-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!