1.2.108. Cannot Use Append For Reading

The append operator [] is used to add a value to an array. It doesn’t provide an existing value to read. Hence, the short assignement operators, or the increment ones should not be used with the append operator. For example, the coalesce operator yields an error when used with append.

<?php

$x = [];
$x[] = 1; // normal usage
$x[] += 2; // adds a 2, but should yield an error
$x[]++;    // adds a 1, but should yield an error
// variations with -= *= &= etc.

$x[] ??= 4; // yields a fatal error

?>

1.2.108.1. Suggestions

  • Remove the short assignement and build a real expression on the right hand of the assignement to append

1.2.108.2. Specs

Short name

Structures/CannotUseAppendForReading

Rulesets

All, Analyze

Exakat since

2.6.3

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

Very high

Available in

Entreprise Edition, Exakat Cloud