You can use the function array_search
to search for values within the array. But if you don’t need to know where the element is, the function in_array
serves the purpose.
The behavior of comparisons between arrays will depend on whether the comparison is strict or not. Where normal comparison checks whether arrays have the same key/value pairs and 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 the 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 code working
It is important to remember that the method array_search
returns the index of the element found in the array or false
if the element is not found. So remember to make a strict comparison, because if the element is in the first position the result will be zero, which is a value falsy (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";
}
Man, I appreciate the answer, very good, but what made my life easier was the
compact()
as in Woss' answer. + 1 anyway!– rbz