PHP Snippet 1:
function allEven(array $values)
{
foreach ($values as $value) {
if (1 === $value % 2) {
return false;
}
}
return true;
}
$data = [
1,
42,
9000,
];
$allEven = allEven($data);
PHP Snippet 2:
<?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)
PHP Snippet 3:
function array_every($array,$callback)
{
return !in_array(false, array_map($callback,$array));
}
array_every([1,2,3],function($n){
return $n>0;
});
PHP Snippet 4:
$bool = !empty(array_filter(['my', 'test', 'array'], function ($item) {
return $item === 'array';
}));
PHP Snippet 5:
$bool = !empty(array_filter(['my', 'test', 'array'], fn($item) => $item === 'array'));
PHP Snippet 6:
let bool = ['my', 'test', 'array'].every(item => item === 'array'));
PHP Snippet 7:
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);
PHP Snippet 8:
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;
}
PHP Snippet 9:
function array_every(callable $callback, array $array) {
foreach ($array as $item) {
if (!$callback($item)) return false;
}
return true;
}
PHP Snippet 10:
$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]
PHP Snippet 11:
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;
};