1.2.1116. Should Use array_column()

Avoid writing a whole slow loop, and use the native array_column().

array_column() is a native PHP function, that extract a property or a index from a array of object, or a multidimensional array. This prevents the usage of foreach to collect those values. array_column() 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 = array(array('b' => 1),
           array('b' => 2, 'c' => 3),
           array(          'c' => 4)); // b doesn't always exists

$bColumn = array_column($a, 'b');

// Slow and cumbersome code
$bColumn = array();
foreach($a as $k => $v) {
    if (isset($v['b'])) {
        $bColumn[] = $v['b'];
    }
}

?>

See also [blog] array_column() and preprocess.

1.2.1116.1. Suggestions

  • Use array_column(), instead of a foreach()

1.2.1116.2. Specs

Short name

Php/ShouldUseArrayColumn

Rulesets

All, Performances, Suggestions

Exakat since

0.10.2

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

Very high

Available in

Entreprise Edition, Exakat Cloud