1.2.70. Avoid array_push()

array_push() is slower than the append [] operator.

This is also true when the append operator is called several times, while array_push() is be called only once, with an arbitrary number of argument.

Using count after the push is also faster than collecting array_push() return value. It is a micro-optimisation.

<?php

$a = [1,2,3];
// Fast version
$a[] = 4;

$a[] = 5;
$a[] = 6;
$a[] = 7;
$count = count($a);

// Slow version
array_push($a, 4);
$count = array_push($a, 5,6,7);

// Multiple version :
$a[] = 1;
$a[] = 2;
$a[] = 3;
array_push($a, 1, 2, 3);

?>

1.2.70.1. Suggestions

  • Use the [] operator

1.2.70.2. Specs

Short name

Performances/AvoidArrayPush

Rulesets

All, Changed Behavior, PHP recommendations, Performances

Exakat since

0.9.1

PHP Version

All

Severity

Minor

Time To Fix

Instant (5 mins)

Precision

Very high

Available in

Entreprise Edition, Exakat Cloud