You can use the array_search
function to search for values within the array . But if you do not need to know where the element is, the in_array
function serves the purpose.
The behavior of comparisons between arrays will depend on whether the comparison is strict or not . Where the normal comparison checks if the arrays have the same key / values pairs and the restricted comparison also checks if they are in the same order. Ex.:
$a = ['a' => 1, 'b' => 2];
$b = ['b' => 2, 'a' => 1];
$a == $b; // true
$a === $b; // false
That said, just use in_array
:
<?php
$permissoes = [
["A" => "X", "B" => "Y", "C" => 1],
["A" => "X", "B" => "Y", "C" => 2],
["A" => "X", "B" => "W", "C" => 1],
["A" => "X", "B" => "W", "C" => 3],
];
$existente = ["A" => "X", "B" => "Y", "C" => 2];
$inexistente = ["A" => "X", "B" => "Y", "C" => 3];
// Printa: "Tem permissão"
if (in_array($existente, $permissoes)) {
echo "Tem permissão";
} else {
echo "Não tem permissão";
}
// Printa: "Não tem permissão"
if (in_array($inexistente, $permissoes)) {
echo "Tem permissão";
} else {
echo "Não tem permissão";
}
Repl.it with the working code
It is important to remember that the array_search
method returns the index of the element found in the array or false
if the element is not found. So remember to make a narrow comparison, because if the element is in the first position the result will be zero, which is a falsy value. (If you use in_array
this is not a problem). Ex:
<?php
$a = [1, 2, 3, 4];
$result = array_search(1, $a);
// Printa: "Não encontrado"
if ($result) {
echo "Encontrado";
} else {
echo "Não encontrado";
}