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.

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

This prints out the following:

Array
(
 [value1] => key1
 [value2] => key2
)

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().

Array
(
 [a] => 2
 [b] => 3
)

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.

if (!function_exists('array_flip')) {
 function array_flip($array){
  $values = array();
  while ( list($key, $val) = each($array) ) {
    $values[$val] = $key;
  }
  return $values;
 }
}

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.