Writing Arr::every and Arr::some Methods in Laravel

LaravelPosted on

Laravel offers a bunch of useful methods in the Arr class. Let’s see how to extend them with two handy methods that are often used.

Arr::every

The every method determines if all the items in the array pass the given truth test. This can be very handy to avoid foreach loops. Let’s see how to extend the Arr class with a macro.

Arr::macro('every', function ($array, $callback) {
    foreach ($array as $key => $value) {
        if (! $callback($value, $key)) {
            return false;
        }
    }

    return true;
});
You may add the macro in a service provider’s boot method.

From this point, we can use the macro easily in our application:

Arr::every([1, 2, 3, 4, 5], function ($item) {
    return $item < 6;
});

// true

Arr::every([1, 2, 3, 4, 5], function ($item) {
    return $item < 3;
});

// false

Arr::some

The difference between every and some is that, while every required all items to pass the truth test, some requires at least one. So, if at least on item passes, it returns true, otherwise false. Let’s see the macro:

Arr::macro('some', function ($array, $callback) { 
    foreach ($array as $key => $value) { 
        if ($callback($value, $key)) {
            return true; 
        } 
    } 

    return false; 
});

After registering the macro, we can use it application-wide:

Arr::some([1, 2, 3, 4, 5], function ($item) {
    return $item < 3;
});

// true

Arr::some([1, 2, 3, 4, 5], function ($item) {
    return $item === 6;
});

// false

Summary

These methods can be a handy extension especially we are working with simpler arrays, yet want to avoid foreach loops.

Please note, this functionality is already is present in collections, however, it can be a bit confusing switching to collections just to perform a check we need.

Need a web developer? Maybe we can help, get in touch!

Similar Posts

More content in Laravel category