View on GitHub

RefactoringPHP

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

Substitute Algorithm (195)

Old Code

<?php
function foundPerson($people) {
    for ( $i = 0; $i < count($people); $i++ ) {
        if ( $people[$i] === 'Don' ) {
            return 'Don';
        }
        if ( $people[$i] === 'John' ) {
            return 'John';
        }
        if ( $people[$i] === 'Kent' ) {
            return 'Kent';
        }
       
    }
    return '';
}

New Code

<?php
function foundPerson($people) {
    $candidates = ['Don','John', 'Kent'];
    $intersect = array_intersect($people,$candidates);
    return array_shift($intersect) ?? '';
}