What are the common pitfalls to avoid when working with nested arrays in PHP, especially in scenarios involving permission hierarchies?
One common pitfall when working with nested arrays in PHP, especially in scenarios involving permission hierarchies, is not properly traversing the nested arrays to check permissions at each level. To avoid this, you should recursively traverse the nested arrays to check permissions at each level and ensure that the correct permissions are being applied at each nested level.
function checkPermission($permissions, $requiredPermission) {
foreach ($permissions as $permission => $value) {
if ($permission === $requiredPermission) {
return true;
}
if (is_array($value)) {
if (checkPermission($value, $requiredPermission)) {
return true;
}
}
}
return false;
}
$permissions = [
'read' => true,
'write' => false,
'delete' => [
'admin' => true,
'user' => false
]
];
$requiredPermission = 'user';
if (checkPermission($permissions, $requiredPermission)) {
echo "Permission granted!";
} else {
echo "Permission denied!";
}