1

I have two arrays: $values and $availableKeys. I want to throw an exception if $values contains not allowed keys. At the moment I am running this code.

    foreach ($values as $key => $value) {
        if (!in_array($key, $availableKeys)) {
            throw new RuntimeException(
                'Not allowed key'
            );
        }
    }

Exists a better way to validate an array? The question Validate PHP Array Key>Value is not responding to my question.

Community
  • 1
  • 1
sensorario
  • 20,262
  • 30
  • 97
  • 159
  • 1
    *Is not satisfying me.* is not a PHP error. Do you get any when you run the code? – D4V1D Jul 24 '15 at 07:56
  • I've update the question removing that sentence. The point is under the code: "Exists a better way to validate an array?" – sensorario Jul 24 '15 at 08:38

3 Answers3

2
if (array_diff_key($values, array_flip($availableKeys))) {
    throw new RuntimeException(..);
}
deceze
  • 510,633
  • 85
  • 743
  • 889
0

i can only say that test, that key is present in array, is more faster. So make array $availableKeys not [key1, key2...] but [key1=>1, key2=>1...]. ie, flip your current array

foreach ($values as $key => $value) {
        if (!isset($availableKeys[$key])) {
            throw new RuntimeException(
                'Not allowed key'
            );
        }
    }
splash58
  • 26,043
  • 3
  • 22
  • 34
0

You could use array_diff() to search for unallowed keys:

$allowedKeys = array("a","b","c");
$test = array("a" => "asdf", "c" => "asdf", "d" => "asdf");
$notAllowedKeys = array_diff(array_keys($test), $allowedKeys);
if($notAllowedKeys) {
    print "One or more keys are not allowed";
    print_r($notAllowedKeys);  
}

Live example: http://3v4l.org/hi2sP

t.h3ads
  • 1,858
  • 9
  • 17
  • Don't use `empty` for variables which are guaranteed to exist. `if ($notAllowedKeys)` does exactly the same thing without needlessly suppressing error reporting. – deceze Jul 24 '15 at 07:58
  • Why shouldn't empty() be used? array_diff() returns an empty array if no difference is found, so why not check an empty array with empty()? – t.h3ads Jul 24 '15 at 08:00
  • 1
    Because you're **needlessly suppressing error reporting.** See [The Definitive Guide To PHP's isset And empty](http://kunststube.net/isset/) – deceze Jul 24 '15 at 08:01
  • What do you mean? In the example a key "b" is not set in $test and it still works. – t.h3ads Jul 24 '15 at 08:49