Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array_key_exists key LIKE string, is it possible?

I've done a bunch of searching but can't figure this one out.

I have an array like this:

$array = array(cat => 0, dog => 1);

I have a string like this:

I like cats.

I want to see if the string matches any keys in the array. I try the following but obviously it doesn't work.

array_key_exists("I like cats", $array)

Assuming that I can get any random string at a given time, how can I do something like this?

Pseudo code:

array_key_exists("I like cats", *.$array.*)
//The value for cat is "0"

Note that I want to check if "cat" in any form exists. It can be cats, cathy, even random letter like vbncatnm. I am getting the array from a mysql database and I need to know which ID cat or dog is.

like image 618
Keith C. Avatar asked Feb 06 '23 21:02

Keith C.


2 Answers

You can use a regex on keys. So, if any words of your string equal to the key, $found is true. You can save the $key in the variable if you want. preg_match function allows to test a regular expression.

$keys = array_keys($array);
$found = false;
foreach ($keys as $key) {
    //If the key is found in your string, set $found to true
    if (preg_match("/".$key."/", "I like cats")) {
        $found = true;
    }
}

EDIT :

As said in comment, strpos could be better! So using the same code, you can just replace preg_match:

$keys = array_keys($array);
$found = false;
foreach ($keys as $key) {
    //If the key is found in your string, set $found to true
    if (false !== strpos("I like cats", $key)) {
        $found = true;
    }
}
like image 91
AnthonyB Avatar answered Feb 08 '23 15:02

AnthonyB


This should help you achieve what you're trying to do:

$array         = array('cat' => 10, 'dog' => 1);

$findThis      = 'I like cats';

$filteredArray = array_filter($array, function($key) use($string){

    return strpos($string, $key) !== false;

}, ARRAY_FILTER_USE_KEY);

I find that using the array_filter function with a closure/anonymous function to be a much more elegant way than a foreach loop because it maintains one level of indentation.

like image 20
useyourillusiontoo Avatar answered Feb 08 '23 14:02

useyourillusiontoo