I'm currently trying to port some JavaScript over to PHP. However, I can't seem to find PHP's equivalent to the JavaScript array.every()
function. I found PHP's each()
function, but it doesn't seem to be exactly what I need.
Definition and Usage. The every() method executes a function for each array element. The every() method returns true if the function returns true for all elements. The every() method returns false if the function returns false for one element.
Create an Array in PHP In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.
To check if all values in an array are equal:Use the Array. every() method to iterate over the array. Check if each array element is equal to the first one. The every method only returns true if the condition is met for all array elements.
forEach(callback) method is an efficient way to iterate over all array items. Its first argument is the callback function, which is invoked for every item in the array with 3 arguments: item, index, and the array itself.
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:
Note foreach
is better than using array_reduce()
because evaluation will stop once a value has been found that doesn't satisfy the specification.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With