1.2.32. Ambiguous Array Index

Indexes should not be defined with different types than int or string.

Array indices only accept integers and strings, so any other type of literal is reported. In fact, null is turned into an empty string, booleans are turned into an integer, and real numbers are truncated (not rounded).

They are indeed distinct, but may lead to confusion.

<?php

$x = [ 1  => 1,
      '1' => 2,
      1.0 => 3,
      true => 4];
// $x only contains one element : 1 => 4

// Still wrong, immediate typecast to 1
$x[1.0]  = 5;
$x[true] = 6;

?>

See also array.

1.2.32.1. Suggestions

  • Only use string or integer as key for an array.

  • Use transtyping operator (string) and (int) to make sure of the type

1.2.32.2. Specs

Short name

Arrays/AmbiguousKeys

Rulesets

All, Analyze, Changed Behavior, Semantics

Exakat since

0.8.4

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

High

Features

array

Examples

PrestaShop, Mautic

Available in

Entreprise Edition, Exakat Cloud