user1372896 user1372896 - 28 days ago 10
PHP Question

Find array value by string key

I have the current array:

$types = array(
"Rifle" => "rifle",
"SMG" => "smg",
"Knife" => "knife",
"Sticker" => "sticker",
"Container" => "case",
"Key" => "key",
"Shotgun" => "heavy",
"Machinegun" => "heavy",
"Music Kit" => "music",
"Graffiti" => "graffiti",
"Tag" => "tag",
);


I'm then wanting to check if my string contains the word from one of the keys, for example "Covert Rifle" should match the first element in the array and return "rifle".

"My Big Container" should then match "Container" and return "case".

Trying to use

array_search("My Big Container", $types);


This doesn't return anything and is FALSE. I take it because my keys are not numerical and are instead strings?

Answer

You could do this:

function getArrayValueBasedOnString($array, $string, $caseSensitive = false){
  $s = $caseSensitive ? '' : 'i';
  foreach($array as $k => $v){
    if(preg_match('/'.preg_quote($k, '/')."/$s", $string)){
      return $v;
    }
  }
  return null;
}
$result = getArrayValueBasedOnString($types, 'My Big Container');

Of course, this will return the very first match. And if you have any null $array values you might want to change that return value.