4

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?

0

3 Answers 3

6
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.

Sign up to request clarification or add additional context in comments.

Comments

1

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!

4 Comments

That does not work like you think it does. Did you test it?
@Wrikken: you were right. I've updated the answer. Please remove the downvote :)
As soon as you implement non-scalar comparison :P (BTW: do we need 2 answers saying array_intersect?)
That's still lossy comparison, but my downvote is at least gone as it would suffice for the OPs testcase ;)
0

If you are seeking a boolean result, PHP8.4's array_all() is a single call which also performs efficiently due to its conditional early return upon false evaluation. Demo

$allowedElements = ['apple', 'orange', 'pear', 'melon'];

$array = ['apple', 'orange'];

var_export(
    array_all(
        $array,
        fn($v) => in_array($v, $allowedElements)
    )
);
// true

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.