0

From a performance perspective, what is the best way to check whether an associated array has and only has a given set of keys? Same question, but from a code conciseness perspective?

function checkArrKeys(array $arr, array $keys):bool {
    $arrKeys=array_keys($arr);
    sort($arrKeys);
    sort($keys);
    return $arrKeys===$keys;
}

function checkArrKeys(array $arr, array $keys):bool {
    return ($cnt = count(array_intersect(array_keys($arr), $keys)))===count($arr) && $cnt===count($keys);
}

function checkArrKeys(array $arr, array $keys):bool {
    return !(array_diff_key($arr, array_flip($keys)) || array_diff_key(array_flip($keys), $arr));
}
user1032531
  • 24,767
  • 68
  • 217
  • 387

4 Answers4

0

Not sure about the performance but this is one way.
Merge the keys with the array_keys and count the values.
Then remove all that had the value 2, if something is left there is a difference.

$merged = array_diff(array_count_values(array_merge($keys, array_keys($arr))), [2]);

https://3v4l.org/ATSHF

Andreas
  • 23,610
  • 6
  • 30
  • 62
0

You can do this simply, by

 function ArrayKeysAreEqual(array $keys, array $arr)
 {
    return array_diff(array_keys($arr), $keys) === array_diff($keys, array_keys($arr)); // return true if matches
 }
0

You could use array_diff() on this with a count() check.

function checkArrKeys(array $arr, array $keys):bool {
    return count(array_diff(array_keys($arr),$keys)) === 0 && count($keys) === count(array_keys($arr));
}
nice_dev
  • 17,053
  • 2
  • 21
  • 35
0

Just compare them:

function checkArrKeys(array $arr, array $keys):bool {
    $arrayKeys = array_keys($arr);
    sort($arrayKeys);

    return $arrayKeys === $keys; // 
}

$a = ['a'=>1, 'b'=>2, 'c'=>3, 'd'=>4];
$A = ['b'=>2, 'c'=>3, 'd'=>4, 'a'=>1];

$b = ['a'=>1, 'b'=>2, 'c'=>3];
$c = ['a'=>1, 'b'=>2, 'c'=>3, 'd'=>4, 'e'=>5];


$keys = ['a','b','c', 'd'];
var_dump(array_keys($a)===$keys); // true
var_dump(array_keys($A)===$keys); // false
var_dump(array_keys($b)===$keys);  // false
var_dump(array_keys($c)===$keys);  // false

function checkArrKeys(array $arr, array $keys):bool {
    $arrayKeys = array_keys($arr);
    sort($arrayKeys);

    return $arrayKeys === $keys; // 
}
echo "\n";

var_dump(checkArrKeys($a, $keys)); // true
var_dump(checkArrKeys($A, $keys)); // true
var_dump(checkArrKeys($b, $keys)); // false
var_dump(checkArrKeys($c, $keys)); // false

Try it online

Martijn
  • 15,791
  • 4
  • 36
  • 68