Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

Thanks!

share|improve this question

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.

share|improve this answer

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!

share|improve this answer
That does not work like you think it does. Did you test it? – Wrikken Aug 15 at 15:17
@Wrikken: you were right. I've updated the answer. Please remove the downvote :) – Amal Murali Aug 15 at 15:37
As soon as you implement non-scalar comparison :P (BTW: do we need 2 answers saying array_intersect?) – Wrikken Aug 15 at 15:44
@Wrikken: alright. Updated again! :P – Amal Murali Aug 15 at 15:52
That's still lossy comparison, but my downvote is at least gone as it would suffice for the OPs testcase ;) – Wrikken Aug 15 at 15:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.