0

I have an array like this fetched from a database:

[0] => Array (
    [permission_id] => 1
    )
[1] => Array (
    [permission_id] => 2
    )

I would like to check if this array contains multiple values with a function. For example:

function checkIfArrayContains($array)
{
    ...
}

$array = array(1, 2);
checkIfArrayContains($array); //Should return true

$array = array(2);
checkIfArrayContains($array); //Should return true

$array = array(1, 2, 3);
checkIfArrayContains($array); //Should return false

How could this be achieved using PHP?

2
  • So basically it gives false if you're testing an array that has a value not present in the first one? Commented Dec 21, 2020 at 12:15
  • @El_Vanja Yes, exactly! Commented Dec 21, 2020 at 12:17

2 Answers 2

1

If you are only getting one column from the database, and you use PDO, I would suggest you use the fetch mode FETCH::COLUMN, to gain an array that looks like

$arr = [1, 2];

Then you can simply use in_array to check for the value

Sign up to request clarification or add additional context in comments.

1 Comment

How do you propose in_array to be used for something like in_array([2], [1, 2])?
1

Here's a suggestion:

$dbPermissions = [
    ['permission_id' => 1],
    ['permission_id' => 2],
];

function hasSufficientPermissions(array $dbPermissions, array $permissions): bool
{
    $dbPermissionValues = array_column($dbPermissions, 'permission_id');
    return empty(array_diff($permissions, $dbPermissionValues));
}

var_dump(hasSufficientPermissions($dbPermissions, [1, 2]));
var_dump(hasSufficientPermissions($dbPermissions, [2]));
var_dump(hasSufficientPermissions($dbPermissions, [1, 2, 3]));

This will output:

true
true
false

How it works:

  • array_column reduces your database array to [1, 2]
  • array_diff finds values in the first array supplied that are not present in the second array supplied
  • if a difference exists, then false should be returned - this is where we utilize empty

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.