Rodrigo
Rodrigo

Reputation: 133

How to search an array key by matching a string in it's value

I'm trying to find the key number in a array matching a string.

I tried array_search in this way

$key = array_search("foo", $array);
echo $array[$key];

but that prints $array[0]

Is there another way to do this?

Thanks :)

Upvotes: 0

Views: 1493

Answers (2)

Rodrigo
Rodrigo

Reputation: 133

I'm not exactly matching the whole string, just one part, will array_search still work?

btw i made a loop through the array with for each that do a preg_match until it finds the string then breaks the loop and store the key in a array

Upvotes: 0

naivists
naivists

Reputation: 33501

If the key is not found, array_search returns false. You have to check for that (line 3 in my example below)

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search("green", $array); //the $key will be "2"
if ($key !== false) {
   echo $array[$key];
}

Otherwise, your code seems to do what you need. If there is a problem, please, post more code.

Upvotes: 2

Related Questions