if (! function_exists('array_all')) { function array_all(array $array, callable $callable) { foreach ($array as $key => $value) { if (! $callable($value, $key)) return false; } return true; }}(PHP 8 >= 8.4.0)
array_all — Verifica se todos os elementos de um array satisfazem uma função de retorno
array_all() retorna true, se a função de retorno
callback retornar true para todos os elementos.
Caso contrário, retorna false.
A função retorna true, se callback retornar
true para todos os elementos. Caso contrário retorna false.
Exemplo #1 Exemplo de array_all()
<?php
$array = [
'a' => 'cachorro',
'b' => 'gato',
'c' => 'vaca',
'd' => 'pato',
'e' => 'elefante',
'f' => 'ganso'
];
// Verifica se todos os nomes de animais têm menos de 12 letras.
var_dump(array_all($array, function (string $value) {
return strlen($value) < 12;
}));
// Verifica se todos os nomes de animais têm mais que 5 letras.
var_dump(array_all($array, function (string $value) {
return strlen($value) > 5;
}));
// Verifica se todas as chaves são strings.
var_dump(array_all($array, function (string $value, $key) {
return is_string($key);
}));
?>O exemplo acima produzirá:
bool(true) bool(false) bool(true)
if (! function_exists('array_all')) { function array_all(array $array, callable $callable) { foreach ($array as $key => $value) { if (! $callable($value, $key)) return false; } return true; }}<?phpfunction array_all(array $array, callable $callback): bool{ return array_reduce($array, fn($r, $e) => $r && $callback($e), true);}?>The function will always return true for empty array.php > var_dump(array_all([], fn()=> true));bool(true)php > var_dump(array_all([], fn()=> false));bool(true)