user701510
user701510

Reputation: 5763

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.

Upvotes: 6

Views: 17990

Answers (3)

AC2MO
AC2MO

Reputation: 1637

Use array_search, here's an example:

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

In your example, this would return 0.

Upvotes: 1

alex
alex

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

deceze
deceze

Reputation: 522005

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

Upvotes: 1

Related Questions