Array Functions

PHP array_flip() Function

Topic: PHP Array ReferencePrev|Next


The array_flip() function flip or exchanges all keys with their associated values in an array, i.e. keys from the array become values and the values from the array become keys.

The following table summarizes the technical details of this function.

Return Value: Returns the flipped array on success, and NULL on failure.
Version: PHP 4+


The basic syntax of the array_flip() function is given with:


The following example shows the array_flip() function in action.

// Defining array
$alphabets = array("a"=>"apple", "b"=>"ball", "c"=>"cat");
// Flipping alphabets array
$result = array_flip($alphabets);


The array_flip() function accepts the following parameter.

Parameter Description
array Required. Specifies an array of key/value pairs to be flipped.

Note: The values of array need to be valid keys, i.e. they need to be either integer or string. If a value has the wrong type that key/value pair will not be included in the result.

More Examples

Here're some more examples showing how array_flip() function basically works:

This function works for both indexed and associative array. Here's an example:

// Defining array
$fruits = array("apple", "banana", "orange", "mango");
// Flipping fruits array
$result = array_flip($fruits);

Also, if a value occur several times, the latest key will be used as its value and all others will be lost. Let's try out the following example to understand how it actually works:

// Defining array
$colors = array("red", "green", "blue", "red", "yellow", "red");
// Flipping colors array
$result = array_flip($colors);
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties