Suppose there is an array
$data = array(
"key1" => "value1",
"key2" => "value2",
"key3" => "value3"
);
And there is a string which may contain one of the keys in this array. And I want the value of this key in the array.
For example, the string is "**^%$key1^&*"
which contains "key1"
. What I want to do is to return the value1
.
This example maybe better for understanding:
$fruits = array(
"apple" => "red",
"avocado" => "green",
"orange" => "orange"
);
When the input is "Gala apple"
I want the output to be "red"
What I can think for now is using foreach.
$str = "Gala apple";
foreach($fruits as $k=>$v) {
if(preg_match('/'.$k.'/i', $str))
return $v;
}
This code works.
But... is there any method can avoid the loop?