PHP array_flip() function is “used to flip/exchange all keys with their associated values in an array.”
Syntax
array_flip($array);
Parameters
$array: It specifies the array of key/value pairs to be flipped.
Return value
It returns a new array with flipped keys and values, NULL on failure.
Visual RepresentationExample 1: How to Use array_flip() Function
<?php
$arr = ["Apple","Google", "Meta","Tesla","X"];
$flip = array_flip($arr);
print_r($flip);
Output
Array
(
[Apple] => 0
[Google] => 1
[Meta] => 2
[Tesla] => 3
[X] => 4
)
Example 2: Removing duplicate values
<?php
$arr = [
5 => "Apple",
10 => "Google",
15 => "Meta",
20 => "Apple",
25 => "X"];
$flip = array_flip($arr);
print_r($flip);
Output
Array
(
[Apple] => 20
[Google] => 10
[Meta] => 15
[X] => 25
)
In the above example, the key ’20’ overwrites ‘5’ for the value “Apple”, and the flipped array uses the values from the original array as keys, and the keys from the original array as values.
Remember one thing it can only flip STRING and INTEGER values. Otherwise, it will give a warning.
That’s it.