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

前端 未结 2 1038
耶瑟儿~
耶瑟儿~ 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: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!

提交回复
热议问题