Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 786
user701510 Avatar asked Jun 27 '11 03:06

user701510


2 Answers

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.
}
like image 158
alex Avatar answered Nov 14 '22 23:11

alex


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

like image 23
deceze Avatar answered Nov 14 '22 21:11

deceze