Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a flat array only contains values from a flat whitelist array

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?

like image 943
fj123x Avatar asked Oct 23 '25 17:10

fj123x


2 Answers

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.

like image 137
Wrikken Avatar answered Oct 26 '25 06:10

Wrikken


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!


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!