'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.



Solution 1:[1]

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.

Solution 2:[2]

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.

Solution 3:[3]

Answers on this page are incomplete and change the semantics of every (JS) / all (Python) and similar functions from other languages. Mapping and reducing are incorrect because they visit every element regardless of their truth value.

We need something that supports a callback for an arbitrary predicate and features early bailout upon locating the first element that fails the predicate function. This answer comes close because it offers early bailout but fails to provide a callback predicate.

We might as well write some/any while we're at it.

<?php

function array_every(array $arr, callable $predicate) {
    foreach ($arr as $e) {
        if (!call_user_func($predicate, $e)) {
             return false;
        }
    }

    return true;
}

function array_any(array $arr, callable $predicate) {
    return !array_every($arr, function ($e) use ($predicate) {
        return !call_user_func($predicate, $e);
    });
}

// sample predicate
function is_even($e) {
    return $e % 2 === 0;
}

var_dump(array_every([0, 1, 2, 3], "is_even")); // => bool(false)
var_dump(array_every([0, 2], "is_even")); // => bool(true)
var_dump(array_any([1, 2], "is_even")); // => bool(true)
var_dump(array_any([1, 3], "is_even")); // => bool(false)

Solution 4:[4]

You can use array_reduce function.

Solution 5:[5]

Php array_every function


function array_every($array,$callback)
{

   return  !in_array(false,  array_map($callback,$array));
}


array_every([1,2,3],function($n){
     return $n>0;
});

Solution 6:[6]

A simple solution:

function array_every(array $array, callable $fn) {
  return (bool)array_product(array_map($fn, $array));
}

Check it online: https://3v4l.org/1D1Ao

It is not optimized and is just a proof of concept. For production I would use a foreach to return false on the first item that does not pass the test.

Solution 7:[7]

Here's another option (really, a lot of the array functions can be used fairly similarly):

$bool = !empty(array_filter(['my', 'test', 'array'], function ($item) {
    return $item === 'array';
}));

or for PHP7.4+, using arrow functions:

$bool = !empty(array_filter(['my', 'test', 'array'], fn($item) => $item === 'array'));

... which looks close-ish to JS:

let bool = ['my', 'test', 'array'].every(item => item === 'array'));

And broken out:

function array_every(array $array, callable $callback) {
    return !empty(array_filter($array, $callback));
}

$myArr = ['my', 'test', 'array'];
$myTest = fn($item) => $item === 'array'; // PHP7.4+
$bool = array_every($myArr, $myTest);

Again, several array functions can be used to return an empty or filled array. Though as someone mentioned above, the actual JS [].every will stop as soon as it gets a true return, which can save significant time if you have a large array to iterate through. I came across this question looking for a quick, functional-programing style code to iterate through just three array items.

Solution 8:[8]

I prepared this solution to be close to JavaScript's Array.prototype.every() as much as possible.

Proposed custom function:

Description:

The array_every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

The array_every() method executes the provided $callback function once for each element present in the array until it finds the one where $callbackreturns a falsy value. If such an element is found, the array_every() method immediately returns false. Otherwise, if $callback returns a truthy value for all elements, every returns true.

Note: Calling this method on an empty array will return true for any condition!

The array_every() method does not mutate the array on which it is called.

array_every(array $array, string|callable $callback, null|string|object $thisArg = null): bool

Parameters:

$array

The array to iterate over.

$callback

A callback function to test for each element, taking four arguments:

       $value - The current value of the element being processed in the array.

       $key (Optional) - The current key of the element being processed in the array.

       $index (Optional) - The index of the current element being processed in the array.

       $array (Optional) - The array being traversed.

$thisArg (Optional)

A value to use as $this when executing the $callback function.

Return value:

true if the $callback function returns a truthy value for every array element. Otherwise, false.

The array_every() function:

function array_every(array $array, string|callable $callback, null|string|object $thisArg = null): bool
{
    $index = 0;

    foreach ($array as $key => $value) {

        $condition = false;

        if (is_null($thisArg)) {
            $condition = call_user_func_array($callback, [$value, $key, $index, $array]);
        } else if (is_object($thisArg) || (is_string($thisArg) && class_exists($thisArg))) {
            $condition = call_user_func_array([$thisArg, $callback], [$value, $key, $index, $array]);
        } else if (is_string($thisArg) && !class_exists($thisArg)) {
            throw new TypeError("Class '$thisArg' not found");
        }

        if (!$condition)
            return false;
        $index++;
    }
    return true;
}

Example 1 (Simple callback function):

$isEven = fn($v) => ($v % 2 === 0);

var_export(array_every([2, 8, 16, 36], $isEven)); // true

Example 2:

If a $thisArg parameter is provided to the array_every() method, it will be used as the $callback's $this value. Otherwise, the value null will be used as its $this value.

class Helper
{
    public function isOlderThan18(int $value): bool
    {
        return $value > 18;
    }

    public static function isVowel(string $character): bool
    {
        return in_array($character, ['a', 'e', 'i', 'o', 'u']);
    }

}

Example 2a) Static class method call:

You may pass the fully qualified class name in the $thisArg argument if the class in question is declared under a namespace.

var_export(array_every(["a", "u", "e"], "isVowel", "Helper")); // true

Example 2b) Object method call:

The $thisArg argument can be an object as well.

var_export(array_every(["Peter" => "35", "Ben" => "16", "Joe" => "43"], "isOlderThan18", (new Helper))); // false

Solution 9:[9]

I wrote these codes first:

function array_every(callable $callback, array $array) {
    $matches = [];
    foreach ($array as $item) {
        if ($callback($item)) {
            $matches[] = true;
        } else {
            $matches[] = false;
        }
    }
    if (in_array(false, $matches)) {
        return false;
    }
    return true;
}

And then wrote the mini version of it:

function array_every(callable $callback, array $array) {
    foreach ($array as $item) {
        if (!$callback($item)) return false;
    }
    return true;
}

Usage:

$array = [1, 2, 3];
$result = array_every(function($item) {
    return $item == 3; // Check if all items are 3 or not (This part is like JS)
}, $array);

echo $result; // Returns false, but returns true if $array = [3, 3, 3]

So both versions works well
And you got the answer! :)

Solution 10:[10]

I wrote this protoype a LONG time ago, back in the dark age of the internet when you never knew what a the browser would do.

Yes, this predates jQuery by a decade.

It's in JS. Use it as a good exercise to learn PHP when you convert this.

A bit late for you but I hope it helps a bit.

  if ( typeof Array.prototype.every !== 'function' )
  {
  Array.every = Array.prototype.every = function( _callBack, _array )
  {
      // Assume failure
      var _matches = false;

      if ( typeof _callBack === 'function' )
      {
          // Use ARRAY Object data or passed in data
          _array = (_array === undefined) ? this : _array;

          // Assume success
          _matches = true;

          var _len = this.length;
          for ( var _i = 0; _i < _len; _i++ )
          {
              // If this failed, bounce out
              if ( ! _callBack(this[_i], _i, _array ) )
                  {
                  _matches = false;
                  break;
              }
          }
      }

      return _matches;
  };

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 localheinz
Solution 3
Solution 4 Tr?ng V?nh Nguy?n
Solution 5
Solution 6 axiac
Solution 7
Solution 8
Solution 9 pouriya
Solution 10 Old Man Walter