0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You should consider preg_quote to escape reserved values of the regex.
Of course, I concur, if you have any weird array keys.
1

array_search is searching for values. If you want to search for the keys, you should transform keys to values using array_keys

$key = array_search("Container", array_keys($types));
if( is_array($key) && count($key) > 0 )
    return $types[$key];

However, array_search will perform an exact match. If you want partial match (one word) or case insensitive or else, then you should not use array_search but loop over all keys and try to find any word

$keys = array_keys($types);
$words = explode(" ", "My Big Container");
$match = null;
foreach( $keys as $k )
    foreach( $words as $w )
        if( $k == $w ) $match = $w;

if( $match !== null )
    return $types[$match];

2 Comments

This will definitely be a multi word search (and potentially case sensitive). What alternative do I have for array_search?
I included a (simple) example of multi word search

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.