php check if an array only contains element values of another array

前端 未结 2 1017
耶瑟儿~
耶瑟儿~ 2021-01-14 06:27

I want to check if an array only contains allowed element values (are available in another array).

Example:

$allowedElements = array(\'apple\', \'ora         


        
相关标签:
2条回答
  • 2021-01-14 06:41
    count($array) == count(array_intersect($array,$valid));
    

    .. or come to think of it;

    $array == array_intersect($array,$valid);
    

    Note that this would yield true if (string)$elementtocheck=(string)$validelement, so in essence, only usable for scalars. If you have more complex values in your array (arrays, objects), this won't work. To make that work, we alter it a bit:

    sort($array);//order matters for strict
    sort($valid);
    $array === array_intersect($valid,$array);
    

    ... assuming that the current order does not matter / sort() is allowed to be called.

    0 讨论(0)
  • 2021-01-14 06:58

    You can use array_intersect() as suggested here. Here's a little function:

    function CheckFunction($myArr, $allowedElements) 
    {
        $check = count(array_intersect($myArr, $allowedElements)) == count($myArr);
    
        if($check) {
            return "Input array contains only allowed elements";
        } else {
            return "Input array contains invalid elements";
        }
    }
    

    Demo!

    0 讨论(0)
提交回复
热议问题