PHP

Custom Function to Check if All Array Elements Satisfy a Condition

Implement a reusable PHP function to verify if every single element in a given array passes a specified condition defined by a callback, returning true or false.

<?php
function array_all(array $array, callable $callback): bool
{
    foreach ($array as $element) {
        if (!$callback($element)) {
            return false; // Found an element that doesn't satisfy the condition
        }
    }
    return true; // All elements satisfied the condition
}

$numbers = [2, 4, 6, 8, 10];
$allEven = array_all($numbers, function($n) {
    return $n % 2 === 0;
});
// $allEven will be true

$mixedNumbers = [1, 2, 3, 4, 5];
$allGreaterThanZero = array_all($mixedNumbers, function($n) {
    return $n > 0;
});
// $allGreaterThanZero will be true

$allGreaterThanThree = array_all($mixedNumbers, function($n) {
    return $n > 3;
});
// $allGreaterThanThree will be false (due to 1, 2, 3)
?>
How it works: PHP lacks a built-in function like `array_all` found in other languages. This custom `array_all` function takes an array and a callback. It iterates through each element, applying the callback. If the callback returns `false` for any element, the function immediately returns `false`. If all elements pass the condition, it returns `true`. This provides a concise way to validate array contents against specific criteria.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs