Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to check that every array element satisfies a condition

Short answer

PHP 8.4 has array_all() and array_any():

<?php
 
$ages = [21, 34, 18];
 
var_dump(array_all($ages, fn ($age) => $age >= 18));
var_dump(array_any($ages, fn ($age) => $age > 60));

Output:

bool(true)
bool(false)

In older versions

Filter the array and compare the counts:

<?php
 
$ages = [21, 34, 18];
 
$adults = array_filter($ages, fn ($age) => $age >= 18);
 
var_dump(count($adults) === count($ages));

Output:

bool(true)

Functions used in this recipe

  • array_all — Checks whether every element satisfies a condition.
  • array_any — Checks whether at least one element satisfies a condition.
  • array_filter — Keeps the array elements that pass a test.

Thanks for reading!

Donate to the site — we work hard for you.