PHP array_flip() Function

What is PHP array_flip() Function?

If you want to exchange/flip all the values with their associated values, use array_flip() function.

Syntax:

array_flip(array)

Parameters:

The Function has 1 parameter which is required –

array (Required): It specifies an array whose key/value to be flipped.

Return Values:

It returns a flipped array where the keys become the values and the values become the keys of the input array.

Examples:

Example 1:

<pre>
<?php
$input_array = array("one", "two", "three");
$flipped_array = array_flip($input_array);
print_r($flipped_array);
?>
</pre>

Output:

Array
(
[one] => 0
[two] => 1
[three] => 2
)

Example 2:

<pre>
<?php
$input_array = array("one", "two", "three", "two");
$flipped_array = array_flip($input_array);
print_r($flipped_array);
?>
</pre>

Output:

Array
(
[one] => 0
[two] => 3
[three] => 2
)

Explanation:

As, there are 2 “two”s in the input array, PHP takes the last one whose key is 3. So, you see the key of the “two” in the flipped array is 3.

Example 3:

<pre>
<?php
$input_array = array("one", "two", "three", 4, 5.5);
$flipped_array = array_flip($input_array);
print_r($flipped_array);
?>
</pre>

Output:

Warning:  array_flip(): Can only flip string and integer values, entry skipped in D:\xampp\htdocs\array_flip.php on line 4

Array
(
[one] => 0
[two] => 1
[three] => 2
[4] => 3
)

Explanation:

As the fifth element of the input array is a float which is not allowed as key of flipped array, so PHP throws the warning and discard this element in the flipped array.

Notes on array_flip() Function:

All the values of the input array need to be either string or integer which is valid as array key.

Caution:

  • If multiple elements of the input array have same values, PHP takes the latest value and exchange it with its key. And PHP leaves the rest out.  See example 2
  • If you use any value in the input array that is not either string or integer, you’ll get a warning and that key/value will not be added in the flipped array. See example 3.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP array_flip() Function:

The array_flip() function is a built-in PHP function and part of the PHP’s array functions. It is a useful way to flip values and keys of an array.