PHP array_flip() Function
The PHP array_flip() function exchanges all keys with their associated values in an array and returns it. Please note that the values of the array need to be valid keys (either int or string). If a value has several occurrences, the latest key is used as its value.
Syntax
array_flip(array)
Parameters
array |
Required. Specify the array of key/value pairs to be flipped. |
Return Value
Returns the flipped array on success and null on failure.
Exceptions
NA.
Example:
The example below shows the usage of array_flip() function.
<?php $Arr = array("Red", "Green", "Blue"); $flipped_Arr = array_flip($Arr); //displaying the result print_r($Arr); echo "\n"; print_r($flipped_Arr); ?>
The output of the above code will be:
Array ( [0] => Red [1] => Green [2] => Blue ) Array ( [Red] => 0 [Green] => 1 [Blue] => 2 )
Example: Values with multiple occurrences
If a value has several occurrences, the latest key is used as its value. Consider the example below:
<?php $Arr = array("Red", "Green", "Blue", "Green", "Blue"); $flipped_Arr = array_flip($Arr); //displaying the result print_r($Arr); echo "\n"; print_r($flipped_Arr); ?>
The output of the above code will be:
Array ( [0] => Red [1] => Green [2] => Blue [3] => Green [4] => Blue ) Array ( [Red] => 0 [Green] => 3 [Blue] => 4 )
Example: using with associative array
Consider one more example where array_flip() function is used with an associative array.
<?php $Arr = array(10=>"Red", 20=>"Green", 30=>"Blue"); $flipped_Arr = array_flip($Arr); //displaying the result print_r($Arr); echo "\n"; print_r($flipped_Arr); ?>
The output of the above code will be:
Array ( [10] => Red [20] => Green [30] => Blue ) Array ( [Red] => 10 [Green] => 20 [Blue] => 30 )
❮ PHP Array Reference