Swapping Array Keys and Values

Dec 06, 2013, by admin

If you want interchange the keys and values of an associative array. It’s very easy, just use PHP’s array_flip() function which perform a very specialized task. It reverses the key-value relationship for all the elements of an associative array and returning a new array that is the mirror image of the original.

Example:

  1. <?php
  2. $opposite_key_value = array(“white” => “black”, “day” => “night”, “open” => “close”);
  3. print_r(array_flip($opposite_key_value));
  4. ?>

Output:

Exchanged keys and values

(“black” => “white”, “night” => “day”, “close” => “open”)