Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@helsont
Last active September 29, 2017 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save helsont/d5f403ae79243a8006417d9ff2121c80 to your computer and use it in GitHub Desktop.
Save helsont/d5f403ae79243a8006417d9ff2121c80 to your computer and use it in GitHub Desktop.
<?php
public function assertKeys($expected, $array)
{
// we want to find if there are differences between the expected keys
// and what the $array has provided. array_diff_key does the job but
// it is incomplete because it is unidirectional:
//
// array_diff_key(['a', 'b'], []) !== array_diff_key([], ['a', 'b']);
// [] !== ['a', 'b']
//
// to fix this, we need to perform the operation in the reverse direction.
// however, some keys may appear twice. so we merge the two array and then
// find the unique values.
//
// why not union? a union "+" operation messes with the indices of an
// array and will return unexpected values.
$result1 = array_diff_key($expected, $array);
$result2 = array_diff_key($array, $expected);
$result = array_unique(array_merge($result1, $result2));
if (count($result) > 0) {
return $result;
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment