3

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?

Sam
  • 7,252
  • 16
  • 46
  • 65
fj123x
  • 6,904
  • 12
  • 46
  • 58

2 Answers2

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

Wrikken
  • 69,272
  • 8
  • 97
  • 136
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!

Community
  • 1
  • 1
  • That does not work like you think it does. [Did you test it](http://codepad.org/Gii7qsUq)? – Wrikken Aug 15 '13 at 15:17
  • @Wrikken: you were right. I've updated the answer. Please remove the downvote :) –  Aug 15 '13 at 15:37
  • As soon as you implement non-scalar comparison :P (BTW: do we _need_ 2 answers saying `array_intersect`?) – Wrikken Aug 15 '13 at 15:44
  • That's still lossy comparison, but my downvote is at least gone as it would suffice for the OPs testcase ;) – Wrikken Aug 15 '13 at 15:56