The PHP array_flip Function is an inbuilt function in PHP which exchanges the keys with their values in the associative array. It returns an array with the corresponding keys and values exchanged. However, the values of the existing array should be valid keys ie. either string or integer. The function throws a warning if the new keys are not valid. In this article, we will discuss the array_flip Function. Also, we will discuss a few examples of using it.
There is only one parameter in the array_flip Function. The parameter should be an array whose keys and values are to be exchanged.
The PHP array_flip Function returns an array with the keys and values exchanged. However, it returns a NULL value if the input values are invalid.
Let us go through a couple of examples to demonstrate.
<?php $testArray = array( 'John' => '10', 'Emma' => '20', 'Chandler' => '30' ); print_r(array_flip($testArray)); ?>
 => John
 => Emma
 => Chandler
In the example above, an array containing an integer as values and name as the key is passed in array_flip function. The keys and values are exchanged in the returned array.
For instance, let’s consider an array containing an invalid value as a key.
<?php $testArray = array( 'John' => '10', 'Emma' => '20', 'Chandler' => array( 'email' => '30', 'age' => 12 ) ); print_r(array_flip($testArray)); ?>
 => John
 => Emma
In the above example, it can be observed that the key Chandler contains an array value which is an invalid key. The PHP array_flip function ignores that value in the output.
Vishesh is currently working as a Lead Software Engineer at Naukri.com. He passed out of Delhi College of Engineering in 2016 and likes to play Foosball. He loves traveling and is an exercise freak. His expertise includes Java, PHP, Python, Databases, Design and Architecture.