View on GitHub

RefactoringPHP

A PHP version of the refactors from Refactoring: Improving the Design of Existing Code (Second Edition) by Martin Fowler

Replace Loop with Pipeline (231)

Note: Due to semantic differences between languages, this sample differs more than most.

Old Code

<?php
$names = [];

foreach($input as $i) {
    if ( $i->job === 'programmer') {
        $names[] = $i->name;
    }
}

New Code

<?php
$names = array_map(
    function ($i) {
        return $i['name'];
    },
    array_filter($input, function ($i) {
        return $i['job'] === 'programmer';
    })
);