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

查看:182
本文介绍了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?

推荐答案

如果您有一个值并想找到该键,请使用

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天全站免登陆