PHP检查如果一个数组只包含另一个数组的元素值 [英] php check if an array only contains element values of another array
问题描述
我要检查,如果一个数组只包含允许的元素值(在另一个阵列可用)。
例如:
$ allowedElements =阵列('苹果','橙','鸭梨','甜瓜');checkFunction(阵列('苹果','橙'),$ allowedElements); // 好checkFunction(阵列('鸭梨','瓜','狗'),$ allowedElements); // KO无效的数组(狗)的元素
什么是实现这个checkFunction($ A,$ b)功能的最佳方式?
计数($数组)==计数(array_intersect($数组$有效));
..或者想起来它;
$阵列== array_intersect($数组$有效);
请注意,这将产生真正
如果(串)$ elementtocheck =(字符串)$ validelement
,所以在本质上,只可用于标量。如果你有你的阵列(数组,对象)在更复杂的价值观,这是不行的。为了使的是的工作中,我们改变了一点:
排序($数组);严格//秩序事项
排序($有效);
$阵列=== array_intersect($有效,$阵列);
... 假设的当前顺序不重要/ 排序()
允许被调用。
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.
这篇关于PHP检查如果一个数组只包含另一个数组的元素值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!