Test if one array is a subset of another

前端 未结 6 1300
庸人自扰
庸人自扰 2021-02-13 05:59

How can I determine if one array is a subset of another (all elements in the first are present in the second)?

 $s1 = \"string1>string2>string3>string4&         


        
6条回答
  •  遇见更好的自我
    2021-02-13 06:54

    If you start from strings, you could check strstr($fullString,$subsetStr);. But that'll only work when all chars have the same order: 'abcd','cd' will work, but 'abcd','ad' won't.

    But instead of writing your own, custom, function you should know that PHP has TONS of array functions, so its neigh on impossible that there isn't a std function that can do what you need it to do. In this case, I'd suggest array_diff:

    $srcString = explode('>','string1>string2>string3>string4>string5');
    $subset = explode('>','string3>string2>string5');
    $isSubset = array_diff($subset,$srcString);
    //if (empty($isSubset)) --> cf comments: somewhat safer branch:
    if (!$isSubset)
    {
        echo 'Subset';
        return true;
    }
    else
    {
        echo 'Nope, substrings: '.implode(', ',$isSubset).' Didn\'t match';
        return false;
    }
    

提交回复
热议问题