What is the array_flip method in PHP?

The array_flip method exchanges the keys and values of an array. This means all the keys are converted to values and all the values are converted to keys.

Syntax

array_flip(array $array_to_flip): array

This method returns a new array.

Code

<?php
$arr = array(1 => "one", 2 => "two", 3 => "three");
echo "The array is \n";
print_r($arr);
echo "\nAfter Flipping \n ";
print_r(array_flip($arr));
?>

In the code above, we created an array.

one => 1
two => 2
three => 3

We then call the array_flip method by passing the created array, which will flip the keys and values of the passed array and return a new array. The returned array will be:

1  => one
2 => two
3 => three

Make sure all the values of the passed array are either string or integer values, otherwise a warning will be thrown and the value will be skipped. For example:

<?php
$arr = array(1 => "one", 2 => array());
print_r(array_flip($arr));
?>

In the code above, the value for the key 2 is an array, which cannot be used as a key, so we will get a warning and that entry will be skipped. The returned array from the array_flip method will be:

one => 1

Free Resources