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 ''.print_r($array, true).'';
This prints out the following:
- [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().
- [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.
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 fucntions included with PHP 5 that you might want to check for when writing code.