Use php array_flip function to exchange keys and associated values in an array

Although array_flip function may appear useless for many, it has a few uses. array_flip function is used to exchange all the keys in the array with their respective values.

Here is an example:

If you’ve read the code well, you could have predicted the output by now:

Array ( [Google] => Android [Microsoft] => Windows Phone [Apple] => iOS )
Array ( [Android] => Google [Windows Phone] => Microsoft [iOS] => Apple )

And that is self explanatory for sure. You see it flipped!

What if array contains values other than String or Integer

In php array key, can either be an integer or a string but a value can be anything. If your array contains values other than an integer or a string, when flipped, it becomes an invalid key. Thus it produces the error message:

“Warning: array_flip(): Can only flip STRING and INTEGER values!”

 

What if array contains duplicate values

When the array you are about to flip contains duplicate values, after flipping it causes duplicate keys. So php replaces the duplicate key, thus you get only the last one and loss all other. Here is an example which demonstrates it

Can you predict the output??

Output

Array ( [0] => cat [1] => dog [2] => cat [3] => cat )

Array ( [cat] => 3 [dog] => 1 )

What happened? [cat]=0 and [cat]=>2 was replaced by [cat]=>3 to prevent duplicate keys. Simple as that! So here is a warning for you:

Warning: Don’t use array_flip function if you have duplicate values in the array which should not be lost.

If there is anything else left, please mention it in comments, I’ll happy to edit my post,

Leave a Reply

Your email address will not be published. Required fields are marked *