Hi,
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 :)
Hi,
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 :)
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.
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