I'm looking to see if an array has one or more values inside it and I want to pass check my values are in that array. I'm going to use it to check role permissions in a system.

example input-output:

[1,2,3,4,5,6].include?([4,1])   => true
[4,1,6,2].include?([4,1])       => true
[3,4,7].include?([4,1])         => false

I tried to solve it using in_array():

if(!$auth->checkPermissions([1,3])) {
    echo json_encode(['Result'=>false,'Type'=>'ERROR','Message'=>UNAUTHORIZED_ACCESS]);
    exit;
}

public static function checkPermissions($permissionLevels = []){
    $userPermission =[1,4,5,6];

    foreach($permissionLevels as $permission){
        if (in_array($permission,$userPermission)) {
            return true;
        } else {
            return false;
        }
    }
    return false;    
}

2 Answers

0
dWinder On Best Solutions

Your problem is happening because you only checking 1 permission as you use return in the foreach.

You should do it like this:

public static function checkPermissions($permissionLevels = []){
    $userPermission =[1,4,5,6];
    foreach($permissionLevels as $permission){
        if (!in_array($permission,$userPermission))
            return false; // if one is missing decline
    }
    return true; // if got here mean all found
}

You can also use array-intersect as:

function checkPermissions($permissionLevels = []){
        $userPermission =[1,4,5,6];
        $permissionLevels = array_unique($permissionLevels);
        return count(array_intersect($permissionLevels, $userPermission)) == count($permissionLevels));
}

Do notice to use array_unique if using the array_intersect as you can have duplicate - consider case where checkPermissions([4,4]);

-1
AbraCadaver On

Just compare the intersection of the two with the permissions to be checked:

return array_intersect($permissionLevels, $userPermission) == $permissionLevels;

See the Demo.