Loops and the search for a one-liner

2016-11-06

Yesterday I stumbled on some code I wrote last year. Inspired by an interview with @adamwathan I started to refactor the code using array functions instead of loops.


// old procedural style

$totalQuantity = 0;

foreach($items as $item) {
    $totalQuantity = $totalQuantity + $item->quantity;
}

// my first attempt

$totalQuantity = array_reduce($items, function($sum, $item) {
    $sum += $item->quantity;
}

It works, but it is not that readable and worse. What does array_reduce() do? It looks more complicated than my first code, a sheep dressed as a wolf.

After a quick tweet with Adam he gave me this tip:

$totalQuantity = array_sum(array_column('quantity'));

We have two PHP-functions combined, but I like array_sum() and array_column(). They have descriptive names, without consulting the documentation you can kind of guess what they do.

But the real kicker was when I discover that my initial array, in fact, is a Laravel collection I could just use this:

$totalQuantity = $items->sum('quantity');

A clear winner!

If you are into this, check out Adam's great book and great podcast.

Back to index


Need a simple way to do git ftp? Take a look at my app GitFTP-Deploy

Subscribe to blog updates