Duveral Duveral - 1 year ago 55
PHP Question

Get duplicate keys from array

I have an array like following and I need to detect all the duplicate keys, not values.

$array1 = array(
"a" => "Mike",
"b" => "Charles",
"b" => "Robert",
"c" => "Joseph"

All the functions I've used are focused on values, and If I apply flip_array(), it's automatically deleting the duplicate keys.

Answer Source

Array-Keys are never duplicates, as they're unique identifiers. (Like Database primary keys)

Declaring $array['b'] twice will cause overriding of the first value.

If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.

Following your logic print_r($array1['b']) would output 2 values, which is impossible.

If you want mulpile values for a key add a dimension:

$array1 = array(
    "a"             => "Mike",
    "b"             => array(1 => "Charles", 2 => "Robert"),
    "c"             => "Joseph"


will return

Array ( [1] => Charles [2] => Robert )


If there's no way around you have to use regular expressions with preg_match and your array as string:

$array1 =' array(
    "a"             => "Mike",
    "b"             => "Charles",
    "b"             => "Robert",
    "c"             => "Joseph"
preg_match_all('/([A-Z])\w+/', $array1, $matches);

will return

 Array ( [0] => Mike [1] => Charles [2] => Robert [3] => Joseph )