How to allow duplicate keys in php array

How to allow duplicate keys in php array

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

How to Allow Duplicate Keys in PHP Arrays

By default, PHP arrays are associative or indexed structures that enforce unique keys. When you attempt to insert a key-value pair where the key already exists, the new value overwrites the old one. This behavior stems from how PHP implements its internal hash table structure for array types. The standard syntax $arr['key'] = $value will never create two distinct entries under the same string or integer key within a single array variable.

However, there are specific scenarios where you need to maintain multiple values associated with what logically appears to be the same key. Achieving this requires moving away from the standard array type and utilizing alternative data structures that explicitly support duplicate keys. The most robust solution involves using PHP's multidimensional arrays or specific classes designed for multi-valued collections.

Using Multidimensional Arrays

The most common and portable approach to handling "duplicate" keys is to wrap every value in an array. Instead of storing a single string or integer at $arr['user'], you store a collection of them. This transforms the structure from a flat map into a list of lists.

// Traditional approach: Only the last value survives
$users = [
    'admin' => 'root',
    'admin' => 'superuser', // Overwrites 'root'
];
echo $users['admin']; // Outputs: superuser

// Multi-dimensional approach: All values are preserved
$users = [
    'admin' => ['value1' => 'root'],
    'admin' => ['value2' => 'superuser'],
];

// Accessing the data requires iterating or specific indexing
foreach ($users as $key => $values) {
    foreach ($values as $subKey => $value) {
        echo "$key: $value\n"; 
    }
}

While this method technically allows you to store multiple entries under the same top-level key, it relies on PHP's internal handling of duplicate keys in arrays. If you assign two items to $users['admin'], the second assignment overwrites the first in memory. The code above actually demonstrates the overwrite issue again unless you append to an existing array. To truly maintain duplicates without overwriting, you must explicitly manage the collection:

$entries = [];
$entries['admin'][] = 'root';
$entries['admin'][] = 'superuser';

// Now accessing requires iteration
foreach ($entries as $key => $list) {
    echo "$key has multiple values\n";
}

This pattern effectively solves the problem by treating each key as a container for an array of values rather than a single scalar. This is the standard idiom in PHP when duplicate keys are conceptually necessary but technically impossible without wrapping.

The SplMultiKeyArray Class

For scenarios where you strictly require a hash table that permits duplicate keys and provides direct access to them, PHP offers the SplMultiKeyArray class introduced in version 8.1. This class is part of the SPL (Standard PHP Library) and behaves like a traditional associative array but allows multiple values for the same key.

$multi = new SplMultiKeyArray();
$multi['key'] = 'value1';
$multi['key'] = 'value2';

// Accessing works differently than standard arrays
echo $multi['key']; // Outputs: value2 (the last one added)
// To get all values, use the specific method provided by the class
print_r($multi->get('key')); // Returns an array containing both values

Using SplMultiKeyArray changes how you interact with the data. You cannot access elements via standard dot notation or simple bracket indexing to retrieve all values; instead, you must use the get() method which returns a collection of all values associated with that key. This distinction is crucial when migrating legacy code or designing APIs that need to support multi-valued keys without forcing a multidimensional structure on the consumer.

Trade-offs and Considerations

Choosing between a multidimensional array and SplMultiKeyArray depends on your specific use case and PHP version constraints. Multidimensional arrays are available in all PHP versions and offer maximum compatibility, though they require slightly more verbose iteration logic to extract individual values. Conversely, SplMultiKeyArray provides a cleaner API for retrieving all values at once but requires PHP 8.1 or later.

It is also important to consider serialization. Standard array structures serialize differently than SplMultiKeyArray. If you plan to store these data structures in a cache (like Redis) or database using serialize(), ensure that your deserialization logic accounts for the specific class type and method signatures required to restore the multi-key state correctly.

If you are building a high-performance application where strict key uniqueness is not a requirement but memory overhead is, wrapping values in arrays adds negligible cost compared to the complexity of managing custom hash tables manually. However, if your data model relies heavily on unique keys for indexing or lookup operations, introducing duplicate keys might violate assumptions made by other parts of your application or database queries. Always validate that downstream consumers can handle the new data structure before implementing it globally.

Our network