1.2.1136. 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 = [['b' => 1],
      ['b' => 2, 'c' => 3],
      ['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().

1.2.1136.1. Connex PHP features

1.2.1136.1.1. Suggestions

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

1.2.1136.1.2. Specs

Short name

Php/ShouldUseArrayColumn

Rulesets

All, Changed Behavior, 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