Is there a PHP equivalent of the JavaScript function Array.prototype.some ()

In JavaScript, we can do:

function isBiggerThan10(element, index, array) { return element > 10; } [2, 5, 8, 1, 4].some(isBiggerThan10); // false [12, 5, 8, 1, 4].some(isBiggerThan10); // true 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

Is there a PHP equivalent of some ()?

+11
javascript php functional-programming
source share
4 answers

No, there is no short circuit in the standard PHP library. There are any number of short circuit-free solutions, among which array_reduce will probably be the best match:

 var_dump(array_reduce([2, 5, 8, 1, 4], function ($isBigger, $num) { return $isBigger || $num > 10; })); 

It might be worthwhile to implement your own functions some / any / all or use a library that provides a set of functional programming primitives like this, for example. https://github.com/lstrojny/functional-php .

+11
source share

This is not included, but they are easy to create. This uses the SRFI-1 names any and every , but can be renamed some and all :

 function array_any(array $array, callable $fn) { foreach ($array as $value) { if($fn($value)) { return true; } } return false; } function array_every(array $array, callable $fn) { foreach ($array as $value) { if(!$fn($value)) { return false; } } return true; } 
+10
source share

Here's array_filter (), which returns a subset of this array based on the return value of this callback. If the subset is empty, then it will be the equivalent of Some () returning false, and if it is not empty, it will correspond to Some () returning true.

 $unfiltered = [1, 11, 2, 22, 3, 33, 4, 44, 5, 55]; $filtered = array_filter ($unfiltered, function ($elem){ return $elem > 10; }); print_r ($unfiltered); print_r ($filtered); var_dump (empty ($filtered)); 

However, this approach is not short-circuited, and performance will be inversely proportional to the size of the array. However, this should not matter in the real world, because the array should still become quite huge, or array_filter is called many times before you notice a performance impact.

If performance is of the utmost importance, you will need to compile the array yourself and exit the loop as soon as you find a match.

 $biggerThanTen = false; foreach ($unfiltered as $elem) { if ($elem > 10) { $biggerThanTen = true; break; } } 
0
source share

Use array_filter and provide a callback. Wrap this in another function to count if there are any results

 function array_some(array $data, callable $callback) { $result = array_filter($data, $callback); return count($result) > 0; } $myarray = [2, 5, 8, 12, 4]; array_some($myarray, function($value) { return $value > 10; }); // true 
-3
source share

All Articles