简体   繁体   中英

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.

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.

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.

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.

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.

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.

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.

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.

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 $callback returns 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

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: :)

My case was I needed to check an array to know if all its values were numbers returning true if all went well. In case there was a string or something else the function had to return false

protected function checkIsNumber($arrayNumbers = []) {
    $ga = NULL;
    foreach($arrayNumbers as $value) { 
        if(is_null($ga)) {
            $ga = is_numeric(trim($value));
        } else {
            $ga = $ga === is_numeric(trim($value));
        }
    }
    
    return $ga;
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM