PHP

PHP

Made by DeepSource

Array contains duplicate keys PHP-W1000

Bug risk
Major

This array contains one or more duplicate keys, which can result in unexpected output. Only the last value associated with the duplicated key will be present in the array.

It is recommended to either make all keys unique or remove the key-value pairs with duplicate keys.

Bad practice

class Symbol
{
    // The constants EQ and IS have the same value here
    private const EQ = '=';
    private const IS = '=';
    private const NEQ = '!=';

    public function map($sign): string
    {
        $array = [
            self::EQ => '= %s',
            self::IS => '== %s', // invalid: self::IS has the same value as self::EQ, meaning the value associated with self::EQ will be overwritten.
            self::NEQ => '!= %s',
        ];

        return $array[$sign];
    }
}

Recommended

class Symbol
{
    // Assign a unique value to each constant
    private const EQ = '=';
    private const IS = '=';
    private const NEQ = '!=';

    public function map($sign): string
    {
        $array = [
            self::EQ => '= %s',
            self::IS => '== %s', // valid: this is okay now since the keys have been fixed.
            self::NEQ => '!= %s',
        ];

        return $array[$sign];
    }
}

References