The PHP array_flip() Function And Detecting Functions

26th June 2008 - 2 minutes read time

The array_flip() function in PHP is used to swap the values of an array with the keys. Take the following array.

$array = array('key1'=>'value1', 'key2'=>'value2');

To exchange all the values with the keys we pass it through the array_flip() function.

  1. $array = array_flip($array);
  2. echo '<pre>'.print_r($array, true).'</pre>';

This prints out the following:

  1. Array
  2. (
  3. [value1] => key1
  4. [value2] => key2
  5. )

If any of the values are the same then the highest key is overwritten. The following array:

$array = array('a', 'a', 'a', 'b');

Will produce the following array when passed through array_flip().

  1. Array
  2. (
  3. [a] => 2
  4. [b] => 3
  5. )

If this bit of code is essential to the running of your program you can make sure that it exists by using the function_exists() function. This function takes a single parameter, which is the name of the function you are testing for as a string. The following code checks to see if the array_flip() function exists, and if not defines a version that works in the same way.

  1. if (!function_exists('array_flip')) {
  2. function array_flip($array){
  3. $values = array();
  4. while ( list($key, $val) = each($array) ) {
  5. $values[$val] = $key;
  6. }
  7. return $values;
  8. }
  9. }

The array_flip() function was included in PHP version 4, so you only need to do this if you expect someone to try and run your code on a very old version of PHP. However, there are many new functions included with PHP 5 that you might want to check for when writing code.

Add new comment

The content of this field is kept private and will not be shown publicly.