3 uses of php array_flip function

Most of them (including me, may be) learn the syntax of all functions but doesn’t learn where to apply those. Thus most of them fail to extract the full potential of their knowledge!

Here are 3 uses of array_flip function in php

1. Search for a value in an array

To search for a value in an array we can use a combination of array_flip and array_key_exists function. Here is an example:

Better use array_search() function to search an array. This tutorial is just for info only.

2. Change case of all elements in an array

You can use a combination of array_flip() and array_change_key_case() function to change the case of all values in an array.

Output

Array ( [0] => CHROME [1] => FIREFOX [2] => OPERA [3] => IE [4] => MAXTHON [5] => DRAGON)

We have just changed the case of all values in the $browsers array. We first flipped the array, changed the case of all keys and then again flipped the array. Simple right?

3. Remove duplicate values from an array

Removing duplicate values from an array can be done by flipping the array twice. Flipping once remove duplicates and convert value to keys. Flipping the second time converts the keys back to values.

Output

Array ( [2] => chrome [4] => firefox [3] => opera )

Using this method preserves the last encountered keys for duplicate values.

You see that keys are not in order. If you want the keys in order 0,1,2 etc you can use a combination of array_keys and array_flip function together

Output

Array ( [0] => chrome [1] => firefox [2] => opera )

And lastly php has prebuild function to remove duplicates! array_unique function exactly does it. I’ve already told you this post is just for info! 😉

Leave a Reply

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