I can’t think of a single, built-in function to do this but you could create a function to abstract the logic into one line. This is hard to explain in words, so take a look at the hadSubset
function I wrote below (and here’s a fiddle demonstrating this: http://sandbox.onlinephpfunctions.com/code/0ae5720559932da69949f44b7a525f5341afa521)
<?php
$permissionsArray = [
['user' => 'bob', 'product_id' => '1'],
['user' => 'bob', 'product_id' => '2'],
['user' => 'bob', 'product_id' => '3'],
['user' => 'sara', 'product_id' => '1']
];
/**
* Checks if $array has $subset
* @param {Array} $array A list of associative arrays
* @param {Array} $subset A list of key=>value's that must all exist in $array
* @return True if subset is found, False if not
*/
function hasSubset($array, $subset) {
foreach ($array as $record) {
if (count(array_intersect($record, $subset)) === count($subset)) return true;
}
return false;
}
echo "Test 1: " . hasSubset($permissionsArray, ['user' => 'bob']);
echo "\nTest 2: " . hasSubset($permissionsArray, ['user' => 'sara']);
echo "\nTest 3: " . hasSubset($permissionsArray, ['user' => 'alice']);
echo "\nTest 4: " . hasSubset($permissionsArray, ['user' => 'bob', 'product_id' => 1]);
echo "\nTest 5: " . hasSubset($permissionsArray, ['user' => 'sara', 'product_id' => 2]);
echo "\nTest 6: " . hasSubset($permissionsArray, ['user' => 'alice', 'product_id' => 3]);
Basically I’m looping through each record in $permissionsArray
and doing an array_intersect
on each with the subset I want. array_intersect
returns an array with the found matches between both, so I just make sure that the number of matches found is the same as the number of indexes in our search.
In your case the subset you want is ['user' => 'bob', 'product_id' => 3]
, so you could do:
if (hasSubset($permissionsArray, ['user' => 'bob', 'product_id' => 3])) {
echo 'Has permission!';
} else {
echo "Doesn't have permission!'";
}
or more generally:
if (hasSubset($permissionsArray, ['user' => $user, 'product_id' => $id])) {
echo 'Has permission!';
} else {
echo "Doesn't have permission!'";
}