如何匹配PHP数组中的值,然后找到键值? [英] how to match value in PHP array and then find key value?
本文介绍了如何匹配PHP数组中的值,然后找到键值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组变量$colorArray = array('red','white','blue');
假设$color = "red";
,如何将$ color的值与$ colorArray匹配,然后找到对应的键值"red"?找到键值"red"后,需要将键值存储在另一个变量中以供其他用途.
Suppose $color = "red";
, how do I match the value of $color with $colorArray and then find the corresponding key value of "red"? After I find the key value of "red", I would then need to store the key value in another variable for other uses.
推荐答案
使用 array_search()
.
$key = array_search($color, $colorArray);
为确保匹配,请确保将其与FALSE
进行比较,而不仅仅是 falsy .
To ensure you got a match, make sure you compare it to FALSE
and not just falsy.
if ($key !== FALSE) {
// Match made.
}
这篇关于如何匹配PHP数组中的值,然后找到键值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文