skip to Main Content

This behavior of PHP has caused me trouble.

<?php
$myArray = ["thing1" => "a", "thing2" => "b", "thing1" => "c"];
var_dump($myArray);

Outputs:

array(2) {
  ["thing1"]=>
  string(1) "c"
  ["thing2"]=>
  string(1) "b"
}

I would be happier if PHP would throw an error in this situation. Is there a way to change this behavior? Sometimes I have a long array and don’t notice that I’ve accidentally defined a key twice. That mistake can be hard to track down.

2

Answers


  1. You could create you own dictionary

    class UniqueKeyDictionary {
     private $data = [];
    
     public function add($key, $value) {
        if (array_key_exists($key, $this->data)) {
            throw new Exception("Duplicate key: $key");
        }
        $this->data[$key] = $value;
     }
    
     public function get($key) {
        return $this->data[$key] ?? null;
     }
    
     public function getAll() {
        return $this->data;
     }
    }
    

    Usage

    try {
      $dict = new UniqueKeyDictionary();
      $dict->add("foo", "bar");
      $dict->add("foo", "baz"); // This will throw an exception
    } catch (Exception $e) {
      echo $e->getMessage();
    }
    
    Login or Signup to reply.
  2. PHP’s behavior with duplicate keys in associative arrays is by design. When you define an array with the same key multiple times, PHP automatically takes the last occurrence of the key and overwrites the previous value without raising any error or warning.

    Why Doesn’t PHP Throw an Error for Duplicate Keys?

    The main reason PHP doesn’t throw an error or warning for duplicate keys is that it’s designed to be a forgiving and loosely typed language. This design philosophy prioritizes flexibility and ease of use, allowing developers to work without having to manage strict type or syntax rules, which includes silently handling duplicate keys in arrays.

    How Can We Handle Duplicate Keys?

    To handle the issue of duplicate keys and catch these scenarios during development, you need to use Static code analysis tools like PHPStan or Psalm can help catch such issues during development. These tools analyze your code and look for potential problems, including duplicate array keys.

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search