获取PHP数组中唯一元素的键 [英] Getting the key of the only element in a PHP array

查看:177
本文介绍了获取PHP数组中唯一元素的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关联数组的键是动态生成的.如何获得此类数组的键"?

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

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

我知道可以通过这样的foreach循环来访问它:

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";

但是,我知道该数组只有一个键,并且希望避免foreach循环.是否可以通过其他任何方式访问此元素的值?或获取密钥名称?

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?

推荐答案

http://php.net/each 说:

每个

警告从PHP 7.2.0开始,此功能已被弃用.强烈建议不要使用此功能.

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

使用 key()很好.
如果您仍要获取该值,则还可以使用 each()

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";

打印dynamic_key -> Value

这篇关于获取PHP数组中唯一元素的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆