Skip to content

Instantly share code, notes, and snippets.

@indeedhat
Created May 22, 2024 18:30
Show Gist options
  • Save indeedhat/64fb0e9593cb7198e03896a31ca4a8bf to your computer and use it in GitHub Desktop.
Save indeedhat/64fb0e9593cb7198e03896a31ca4a8bf to your computer and use it in GitHub Desktop.
Check php array against a shape
<?php
function array_has_missing_keys(array $shape, array $payload, ?array &$missing): bool
{
foreach ($shape as $k => $v) {
if (!is_array($v)) {
if (!array_key_exists($v, $payload)) {
$missing[] = $v;
}
continue;
}
$diff = [];
if (array_has_missing_keys($shape[$k], $payload[$k] ?? [], $diff)) {
$missing[$k] = $diff;
} elseif (!array_key_exists($k, $payload)) {
$missing[] = $k;
}
}
return !empty($missing);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment