Numerically Indexed Arrays
ID |
php.numerically_indexed_arrays |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Php |
Tags |
arrays, reliability |
Description
Reports a negative integer literal used as an array subscript ($a[-1]) or as an explicit array
key ([-1 ⇒ 'x']). Variable or computed indices are not flagged because their value cannot be
known statically.
Rationale
In some languages a negative subscript counts back from the end of a sequence. PHP does no such
thing: $a[-1] is an ordinary lookup of the integer key -1, which usually does not exist and
returns null together with an "Undefined array key" warning. A negative literal key in an array
constructor is equally surprising and is almost always a typo or a mistaken assumption about
end-relative indexing.
<?php
$a = [10, 20, 30];
$last = $a[-1]; // FLAW - key -1 does not exist, yields null + warning
$bad = [-1 => 'x']; // FLAW - negative literal key
$ok = $a[0]; // OK - valid index
$dyn = $a[$i]; // OK - variable index, value unknowable
Remediation
To read the last element use a function that understands end-relative access, such as
end($a) or $a[array_key_last($a)]. If a negative key was intended literally, make that intent
explicit and ensure the value is stored under the same key first.