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()
array_flip( array)
where
Parameter | Description |
---|---|
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
<?php $array1 = array("a"=>"apple", "b"=>"banana"); $result = array_flip($array1); print_r($array1); echo "<br>After flip operation...<br>"; print_r($result); ?>
Output
2. If there are keys with similar values in the array
In this example, we will take an array, where there are two key-value pairs with same value. When we pass this array as argument to array_flip() function, only the last key-value pair of lot whose values are same makes it to returned array.
PHP Program
<?php $array1 = array("a"=>"apple", "b"=>"banana", "p"=>"apple"); $result = array_flip($array1); print_r($array1); echo "<br>After flip operation...<br>"; print_r($result); ?>
Output
3. array_flip() with Indexed Array
In this example, we will take an indexed array and pass it to array_flip() function. Indexed Arrays have index like Associated Arrays have key. So the same explanation for associated arrays hold for indexed arrays, when index is considered as index.
PHP Program
<?php $array1 = array("apple", "banana"); $result = array_flip($array1); print_r($array1); echo "<br>After flip operation...<br>"; print_r($result); ?>
Output
Conclusion
In this PHP Tutorial, we learned how to flip or exchange keys with their values in an array, using PHP Array array_flip() function.