Skip to content
Advertisement

Search for multiple sequences within an array

I want to search within an array that I have. The elements to be searched in this array are out of order, their content will be checked only by matching their keys. I could not reach the correct result in a kind of multiple search

$array = array(
"31113591" => array("41641105", "56073345", "58624587"),
"67391666" => array("61511566"),
"12337372" => array("00331237")
);

$search1 = array("31113591" => array("41641105", "56073345"), "67391666" => array("61511566")); //true
$search2 = array("31113591" => array("41641105"));  //true
$search3 = array("12337372" => array("00331237"), "67391666" => array("61511566")); //true
$search4 = array("67391666" => array("61511566"), "31113591" => array("56073345")); //true
$search5 = array("31113591" => array("41641105", "56273345"), "67391666" => array("61511566")); //false no in-array matches (56273345)
$search6 = array("31113591" => array("41141105"));  //false no in-array matches (41141105)
$search7 = array("31113591" => array("41641105", "56073345", "58624587", "542425624")); //false no in-array matches (542425624)

I want to search $search variable in $array variable I want to get true or false value back

Code i tested myself failed

function filter_array_search($array, $search)
{
   $result = false;
    foreach ($array as $key => $value)
    {
      foreach ($search as $k => $v)
      {         
        if (!isset($array[$k]))
            continue 2;
        else{
            foreach($array[$k] as $fv)
            {
                if(!in_array($fv, $v))
                    continue 3;
            }
        }
      }
      $result = true;
    }
    return $result;
}

Advertisement

Answer

If I understand correctly, this should do it for you.

function search(array $array, array $search) : bool
{
    foreach ($search as $searchKey => $searchArray) {
        // Extra key in the search array is invalid
        if (!array_key_exists($searchKey, $array)) {
            return false;
        }
        
        // Look for extra items in the search array
        if (count(array_diff($searchArray, $array[$searchKey]))) {
            return false;
        }
    }

    return true;
}

The test for this code produces 4 true and 3 falses which matches what you provided.

assert(true === search($array, $search1));
assert(true === search($array, $search2));
assert(true === search($array, $search3));
assert(true === search($array, $search4));
assert(false === search($array, $search5));
assert(false === search($array, $search6));
assert(false === search($array, $search7));

The array_diff function is the magic because it:

Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.

So if there’s anything “extra” in the search it will return that, otherwise it returns an empty array

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement