PHP如果in_array()如何拿到钥匙呢? [英] PHP if in_array() how to get the key as well?

查看:106
本文介绍了PHP如果in_array()如何拿到钥匙呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个微小的问题所困扰。

Struggling with a tiny problem.

我有一个数组:

Array
(
    [0] => 
    [6] => 6
    [3] => 5
    [2] => 7
)

我检查,如果设定值是数组中

I am checking if a set value is in the array.

if(in_array(5, $array)) {
//do something
} else {
// do something else
}

问题是,当它发现阵列值5,我真的需要钥匙一起工作我的做一些事情。

The thing is, when it find the value 5 in array, I really need the key to work with in my "do something".

在这种情况下,我需要设置:

In this case I need to set:

$key = 3;

(从发现价值in_array键)。

(key from the found value in_array).

有什么建议?

推荐答案

array_search() 是你在找什么。

array_search() is what you are looking for.

if (false !== $key = array_search(5, $array)) {
    //do something
} else {
    // do something else
}

这篇关于PHP如果in_array()如何拿到钥匙呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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