开发者

how to match value in PHP array and then find key value?

开发者 https://www.devze.com 2023-03-15 18:49 出处:网络
I have an array variable $colorArray = array(\'red\',\'white\',\'blue\'); Suppose $color = \"red\";, how do I match the value of $color with $colorArray and then find the corresponding key value of \

I have an array variable $colorArray = array('red','white','blue');

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.


Use array_search().

$key = array_search($color, $colorArray);

To ensure you got a match, make sure you compare it to FALSE and not just falsy.

if ($key !== FALSE) {
   // Match made.
}


You're looking for array_search: http://www.php.net/array_search


Use array_search, here's an example:

$key = array_search($color, $colorArray);

In your example, this would return 0.

0

精彩评论

暂无评论...
验证码 换一张
取 消