In this tutorial, you shall learn about PHP array_flip() function which can flip keys with values in the array, with syntax and examples.

PHP array_flip() Function

The array_flip() function exchanges all keys with their associated values in an array.

If two are more keys have same values, array_flip() will use later key-value pair and will replace the prior, since keys are unique.

If you flip indexed arrays, value becomes key and index will become value.

Syntax of array_flip()

</>
Copy
array_flip( array)

where

ParameterDescription
array[mandatory] The array whose key/value pairs has to be flipped

Function Return Value

If flip operation is successful, then array_flip() returns the flipped array, else array_flip() returns NULL.

Examples

1. Flip all keys with values in the array

In this example, we will take an array, with two key-value pairs. We will pass this array as argument to array_flip() function. The function returns an array with keys and values exchanged.

PHP Program

</>
Copy
<?php
$array1 = array("a"=>"apple", "b"=>"banana");
$result = array_flip($array1);
print_r($array1);
echo "<br>After flip operation...<br>";
print_r($result);
?>

Output