Duplicate Array Key

ID

php.duplicate_array_key

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Php

Tags

reliability, suspicious

Description

Reports an array literal ([ …​ ] or array( …​ )) that gives the same constant key more than once, for example ['a' ⇒ 1, 'a' ⇒ 2] or [0 ⇒ 'x', 0 ⇒ 'y']. The later entry is flagged.

Rationale

When the same key appears twice in an array literal PHP keeps only the last value and silently discards the earlier ones, with no warning. This is almost always a copy-paste error: the author meant to use a different key or a different value. Only constant keys (string and numeric literals) are compared; dynamic keys (variables, function calls, constants, interpolated strings) and positional entries without an explicit key are ignored because their value cannot be decided statically.

<?php
$config = [
    'host' => 'localhost',
    'port' => 8080,
    'host' => '127.0.0.1',   // FLAW — key 'host' repeated; 'localhost' is silently dropped
];

$ok = [
    'host' => 'localhost',
    'port' => 8080,          // OK — every key is distinct
];

Remediation

Decide which value is correct and keep a single entry for the key, or rename one of the duplicated keys to the key that was actually intended.

References