Created
May 22, 2024 18:30
-
-
Save indeedhat/64fb0e9593cb7198e03896a31ca4a8bf to your computer and use it in GitHub Desktop.
Check php array against a shape
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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