Skip to main content

Exchange array keys \ values

Exchange keys with values and vice-versa from an associative array can be a very common problem. Let's how we can solve it:

PHP: Using the array_flip function

This native function will do the job on the fly!


<?php
var_dump( array_flip( array('a', 'b', 'c') )  );

Javascript: using an underscore.js method

If you use underscore.js, you have the invert method.


_.invert([1, 2]);

Javascript: building a new array

We can easily build a function to emulate the PHP array_flip function


function array_flip(trans)
{
   var key, tmp_ar = {};
   for ( key in trans )
   {
       if ( trans.hasOwnProperty( key ) )
       {
           tmp_ar[trans[key]] = key;
       }
   }
   return tmp_ar;
}

Python: using a dictionary structure

There's a good way to create an associative array and exchange values with Python using the dictionary structure.


a = dict()
a['one'] = 1
a['two'] = 2
res = dict((v,k) for k,v in a.iteritems())
print res