Home >Backend Development >PHP Tutorial >How to Handle Duplicate Keys in PHP Associative Arrays?
An associative array is a data structure that stores key-value pairs, allowing efficient retrieval of values based on their associated keys. However, by default, associative arrays do not allow duplicate keys.
Consider the following code:
function array_push_associative(&$arr) { $args = func_get_args(); foreach ($args as $arg) { if (is_array($arg)) { foreach ($arg as $key => $value) { $arr[$key] = $value; $ret++; } } else { $arr[$arg] = ""; } } return $ret; }
This function attempts to add values to an associative array, but overwrites any existing key with the same name. For instance, if you use it to create an array like this:
$arr = []; array_push_associative($arr, ['42' => 56], ['42' => 86], ['42' => 97]);
...you'll end up with:
$arr = ['42' => 97];
To overcome this limitation, consider constructing a nested array structure. Instead of having duplicate keys, you can use unique keys that correspond to arrays containing multiple elements. For example:
$arr = [ '42' => [56, 86, 97], '51' => [64, 52], ];
This way, you can access multiple entries associated with the same identifier via the nested array structure.
The above is the detailed content of How to Handle Duplicate Keys in PHP Associative Arrays?. For more information, please follow other related articles on the PHP Chinese website!