How to match a value in a PHP array and then find the key value?

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

Assume $color = "red"; , how do I match the value of $ color with $ colorArray and then find the corresponding key value "red"? After I find the key value of "red", then I will need to save the key value in another variable for other purposes.

+6
source share
3 answers

Use array_search() .

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

To make sure you get a match, make sure you compare it to FALSE , not just fake.

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

You are looking for array_search : http://www.php.net/array_search

+1
source

Use array_search , here is an example:

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

In your example, this will return 0.

+1
source

Source: https://habr.com/ru/post/891415/


All Articles