In this tutorial, we will introduce the way to remove duplicate elements from a php array using php array_flip() function.
PHP array_flip() function can exchange the key and value of a php array. In order to use it to remove elements from an array, we can do as follows:
1. Create an array which contains some duplicate elements
<?php $a = array(1, 5, 2, 5, 1, 3, 2, 4, 5); print_r($a); ?>
The php array $a is:
Array
(
[0] => 1
[1] => 5
[2] => 2
[3] => 5
[4] => 1
[5] => 3
[6] => 2
[7] => 4
[8] => 5
)
2. Flip php array key and value using array_filp()
<?php $a = array_flip($a); print_r($a); ?>
Then $a will be:
Array
(
[1] => 4
[5] => 8
[2] => 6
[3] => 5
[4] => 7
)
3. Use array_flip() again
<?php $a = array_flip($a); print_r($a); ?>
The array $a is:
Array
(
[4] => 1
[8] => 5
[6] => 2
[5] => 3
[7] => 4
)
4. Re-order the array keys
<?php $a= array_values($a); print_r($a); ?>
Finally, $a is:
Array
(
[0] => 1
[1] => 5
[2] => 2
[3] => 3
[4] => 4
)
It does not contain any duplicate elements.