Reputation: 5763
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.
Upvotes: 6
Views: 17990
Reputation: 1637
Use array_search, here's an example:
$key = array_search($color, $colorArray);
In your example, this would return 0.
Upvotes: 1
Reputation: 490143
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.
}
Upvotes: 14