how to match value in PHP array and then find key value?
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.
精彩评论