2

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.

2
  • 1
    Is not satisfying me. is not a PHP error. Do you get any when you run the code? Commented Jul 24, 2015 at 7:56
  • I've update the question removing that sentence. The point is under the code: "Exists a better way to validate an array?" Commented Jul 24, 2015 at 8:38

3 Answers 3

3
if (array_diff_key($values, array_flip($availableKeys))) {
    throw new RuntimeException(..);
}
Sign up to request clarification or add additional context in comments.

Comments

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'
            );
        }
    }

Comments

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

4 Comments

Don't use empty for variables which are guaranteed to exist. if ($notAllowedKeys) does exactly the same thing without needlessly suppressing error reporting.
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()?
Because you're needlessly suppressing error reporting. See The Definitive Guide To PHP's isset And empty
What do you mean? In the example a key "b" is not set in $test and it still works.

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.