1

This is probably a duplicate but I can't find my answer so...

What is the simplest way to do the following:

$valid_keys = ['a','b','c'];

$my_array = ['a'=>'foo', 'd'=>'bar'];

$my_other_array = ['a'=>'foo', 'b'=>'bar'];

array_has_invalid_keys($my_array, $valid_keys);
> true

array_has_invalid_keys($my_other_array, $valid_keys);
> false

Basically I want to check if my_array has any keys that are not in the valid_keys array

5
  • This is not a correct php syntax Commented Jun 25, 2020 at 22:07
  • My bad, should be better now Commented Jun 25, 2020 at 22:08
  • php also needs ; :) Commented Jun 25, 2020 at 22:12
  • Can you tell I'm a pythonista at heart? lol Commented Jun 25, 2020 at 22:12
  • 1
    $result = count(array_diff(array_flip($my_array), $valid_keys)) > 0 ? true : false; Commented Jun 25, 2020 at 22:26

2 Answers 2

2
<?php
    
$valid_keys = ['a', 'b', 'c'];
$my_array = ['a' => 'foo', 'd' => 'bar'];

$ret = array_has_invalid_keys($my_array, $valid_keys);

var_dump($ret);

function array_has_invalid_keys($my_array, $valid_keys) {
    $keys = array_keys($my_array);
    $invalid_keys = array_diff($keys, $valid_keys);

    return !empty($invalid_keys);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Won't this also return false if there are any keys in $valid_keys that aren't used in $my_array? I'll edit my question to be more clear, I want more of a 1-way comparison
phpdocs say, array_diff returns an array containing all the entries from array1 that are not present in any of the other arrays.
try it with $my_other_array as per your example, and it will return false
0
<?php
$valid_keys = ['a','b','c'];

function array_has_invalid_keys(array $array, array $valid_keys) : bool {
    foreach(array_keys($array) as $k) {
        if (!in_array($k, $valid_keys))
            return true;
    }
    return false;
}

array_has_invalid_keys(['a'=>'foo', 'b'=>'bar'], $valid_keys); // false
array_has_invalid_keys(['a'=>'foo', 'd'=>'bar'], $valid_keys); // 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.