+4 votes
in Programming Languages by (71.8k points)

I have an associative array and want to exchange all keys with their associated values and vice versa.

For example,

From

Array

(

    [a] => apple

    [b] => ball

    [c] => cricket

    [d] => dog

    [e] => elephant

)

To

Array

(

    [apple] => a

    [ball] => b

    [cricket] => c

    [dog] => d

    [elephant] => e

)

How can I do this? 

1 Answer

+1 vote
by (351k points)
selected by
 
Best answer

You can use the array_flip() function to flip all keys with their associated values and vice versa.

Here is your example:

I have used PHP terminal and hence all statements start with "php >".

php > $var = array("a"=>"apple","b"=>"ball","c"=>"cricket","d"=>"dog", "e"=>"elephant");
php > $v=array_flip($var);
php > print_r($v);
Array
(
    [apple] => a
    [ball] => b
    [cricket] => c
    [dog] => d
    [elephant] => e
)
php > print_r($var);
Array
(
    [a] => apple
    [b] => ball
    [c] => cricket
    [d] => dog
    [e] => elephant
)


...