PHP - 获取数组值的键名 [英] PHP - Get key name of array value

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

问题描述

我有一个数组如下:

function example() {
    /* some stuff here that pushes items with
        dynamically created key strings into an array */

    return array( // now lets pretend it returns the created array
        'firstStringName' => $whatEver,
        'secondStringName' => $somethingElse
    );
}

$arr = example();

// now I know that $arr contains $arr['firstStringName'];

我需要找出 $arr['firstStringName'] 的索引,以便我能够遍历 array_keys($arr) 并返回键字符串'firstStringName' 通过它的索引.我该怎么做?

I need to find out the index of $arr['firstStringName'] so that I am able to loop through array_keys($arr) and return the key string 'firstStringName' by its index. How can I do that?

推荐答案

如果你有一个值并且想找到这个键,使用 array_search() 像这样:

If you have a value and want to find the key, use array_search() like this:

$arr = array ('first' => 'a', 'second' => 'b', );
$key = array_search ('a', $arr);

$key 现在将包含值 'a' 的键(即 'first').

$key will now contain the key for value 'a' (that is, 'first').

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

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