1.2.71. Avoid array_unique()

The native function array_unique() is much slower than using other alternatives, such as array_count_values(), array_flip()/array_keys(), or even a foreach() loops.

<?php

// using array_unique()
$uniques = array_unique($someValues);

// When values are strings or integers
$uniques = array_keys(array_count_values($someValues));
$uniques = array_flip(array_flip($someValues))

//even some loops are faster.
$uniques = [];
foreach($someValues as $s) {
    if (!in_array($uniques, $s)) {
        $uniques[] $s;
    }
}

?>

See also array_unique..

1.2.71.1. Suggestions

  • Upgrade to PHP 7.2

  • Use an alternative way to make values unique in an array, using array_count_values(), for example.

1.2.71.2. Specs

Short name

Structures/NoArrayUnique

Rulesets

All, Performances

Exakat since

0.8.4

PHP Version

With PHP 7.2 and older

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

Very high

Features

array

Available in

Entreprise Edition, Exakat Cloud