I want to check if an array only contains allowed element values (are available in another array).
Example:
$allowedElements = array('apple', 'orange', 'pear', 'melon');
checkFunction(array('apple', 'orange'), $allowedElements); // OK
checkFunction(array('pear', 'melon', 'dog'), $allowedElements); // KO invalid array('dog') elements
What is the best way to implement this checkFunction($a, $b) function?
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";
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.