1.2.1117. Should Use array_filter()

Should use array_filter().

array_filter() is a native PHP function, that extract elements from an array, based on a custom call. Using array_filter() shortens your code, and allows for reusing the filtering logic across the application, instead of hard coding it every time. array_filter() is faster than foreach() (with or without the isset() test) with 3 elements or more, and it is significantly faster beyond 5 elements. Memory consumption is the same.

<?php

$a = range(0, 10); // integers from 0 to 10

// Extracts odd numbers
$odds = array_filter($a, function($x) { return $x % 2; });
$odds = array_filter($a, 'odd');

// Slow and cumbersome code for extracting odd numbers
$odds = array();
foreach($a as $v) {
    if ($a % 2) { // same filter than the closure above, or the odd function below
        $bColumn[] = $v;
    }
}

function foo($x) {
    return $x % 2;
}

?>

See also array_filter.

1.2.1117.1. Suggestions

  • Use array_filter()

1.2.1117.2. Specs

Short name

Php/ShouldUseArrayFilter

Rulesets

All, Suggestions

Exakat since

1.0.7

PHP Version

All

Severity

Minor

Time To Fix

Slow (1 hour)

Precision

Very high

Examples

xataface, shopware

Available in

Entreprise Edition, Exakat Cloud