phparraysassociative-arrayarray-flip

Swap an array element's key and value


Is there a function which makes:

$array['blue'] = 'Color';

To:

$array['Color'] = 'blue'

And also, is there a limit on what characters can go inside an array index?


Solution

  • array_flip() exchanges all keys with their associated values in an array. Any characters can be used in the key, however keep in mind that keys must be unique, so:

    $array['blue'] = 'Color';
    $array['red']  = 'Color';
    $array = array_flip($array);
    

    Yields only:

    Array
    (
        [Color] => red
    )