What is PHP's equivalent of JavaScript's "array.every()"?

Use a for loop with an early return.

PHP does not have a native function that performs the same function as Javascript's array#every.


Use foreach():

function allEven(array $values) 
{
    foreach ($values as $value) {
        if (1 === $value % 2) {
            return false;
        }
    }

    return true;
}

$data = [
    1,
    42,
    9000,
];

$allEven = allEven($data);

For reference, see:

  • http://php.net/manual/en/function.array-reduce.php

Note foreach is better than using array_reduce() because evaluation will stop once a value has been found that doesn't satisfy the specification.

Tags:

Javascript

Php