Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 761
Joshua Sandoval Avatar asked Jul 18 '17 02:07

Joshua Sandoval


People also ask

What is every () in JavaScript?

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.

What are the 3 types of PHP arrays?

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.

How do you check all the values in an array?

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.

Which array method should you apply to run a function for every item within an array returning an array of all items for which the function is true?

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.


2 Answers

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.

like image 171
Bricky Avatar answered Sep 19 '22 02:09

Bricky


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.

like image 22
localheinz Avatar answered Sep 20 '22 02:09

localheinz