I want to check if an array only contains allowed element values (are available in another array).
Example:
$allowedElements = array(\'apple\', \'ora
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.
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";
}
}