2

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?

Linda
  • 21
  • 4
  • Are alphanumerical characters the only ones you want to keep in the string? http://stackoverflow.com/questions/659025/how-to-remove-non-alphanumeric-characters – chris85 Jan 20 '17 at 15:10
  • @chris85 that was a bad example, I have updated the question and I just want the string to match the key in array. – Linda Jan 20 '17 at 15:39

2 Answers2

0

Why not just use strpos ?

$data = array(
    "key1" => "value1",
    "key2" => "value2",
    "key3" => "value3",
);

$str = "!&!%key3!@#$$";
for($data as $key=>$value) {
    if (strpos($str, $key) !== false) {
        return $value;
    }
}
0

If the only alphanumerics chars in the key string are the valid key, you can strip the other chars using a function such as $result = preg_replace("/[^a-zA-Z0-9]+/", "", $s); from this SO post.

If you know the key, you can directly access the value using this syntax:
$array[$key]

Sample code:

$array = array(
    "key1" => "val1",
    "key2" => "val2",
    "key3" => "val3",
    "key4" => "val4",
    );
echo $array["key2"];

This will echo val2.

To verify if a key exists, you may use isset($array[$key]) or the array_key_exists($key, $array) method.

Community
  • 1
  • 1
Antony
  • 1,253
  • 11
  • 19