The php array_flip() function interchanges the keys and values of an array, making a new array with keys which are the given array’s values and values which are the given array’s keys.
$array = array('bear', 'elephant', 'rabbit');
$flipped_array = array_flip($array1);
print_r($array);
print_r($flipped_array);
// Output:
Array
(
[0] => bear
[1] => elephant
[2] => rabbit
)
Array
(
[bear] => 0
[elephant] => 1
[rabbit] => 2
)
When working with collections of data in php, the ability to manipulate them and create new collections is very valuable.
One such manipulation is the ability to flip the keys and values of an array and create a new array in php.
To flip the keys and values of an array, we can use the php array_flip() function.
The php array_flip() function interchanges the keys and values of an array.
Below is a simple example of using array_flip to flip an array.
$array = array('bear', 'elephant', 'rabbit');
$flipped_array = array_flip($array1);
print_r($array);
print_r($flipped_array);
// Output:
Array
(
[0] => bear
[1] => elephant
[2] => rabbit
)
Array
(
[bear] => 0
[elephant] => 1
[rabbit] => 2
)
Using array_flip() to Remove Duplicates from Array in php
One example of using array_flip() is that you can remove all of the duplicates from a php array with the array_flip() function.
We can take advantage of the fact that an array cannot have duplicate keys and call array_flip() twice.
Below is how to use the array_flip() function to remove duplicates from an array. After using array_flip() twice, we can use array_values() to reindex the array.
$example = array(1,2,4,7,5,4,1,2,3,3,3,4,4,5,5,5,6);
print_r(array_values(array_flip(array_flip($example))));
//Output:
Array
(
[0] => 1
[1] => 2
[2] => 4
[3] => 7
[4] => 5
[5] => 3
[6] => 6
)
Hopefully this article has been useful for you to learn about how to use the php array_flip() function.