6

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.

1

3 Answers 3

14

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.
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

Use array_search, here's an example:

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

In your example, this would return 0.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.