How to Use PHP’s array_flip() to Reverse Keys and Values
This guide explains PHP’s array_flip() function, showing its syntax, parameters, return values, example usage, handling of duplicate values, and important caveats for reliable key‑value reversal.
In PHP, the array_flip() function is a commonly used utility that swaps the keys and values of an array, returning a new array with the inverted mapping.
Basic Syntax
array array_flip ( array $array )Parameter
$array– the input array to be flipped.
Return Value
The function returns the flipped array. If the argument is not a valid array, it returns bool(false).
Simple Example
$array = array(
'a' => 'apple',
'b' => 'banana',
'c' => 'cherry'
);
$flippedArray = array_flip($array);
print_r($flippedArray);Output:
Array
(
[apple] => a
[banana] => b
[cherry] => c
)This demonstrates creating an associative array, applying array_flip(), and printing the result.
Handling Duplicate Values
If the original array contains duplicate values, only the last key for each duplicated value is retained after flipping, because keys must be unique. Example:
$array = array(
'a' => 'apple',
'b' => 'banana',
'c' => 'banana'
);
$flippedArray = array_flip($array);
print_r($flippedArray);Output:
Array
(
[apple] => a
[banana] => c
)Here the earlier key 'b' is overwritten by the later key 'c' because both map to the same value 'banana'.
Important Caveats
When using array_flip(), ensure that the original array’s values are unique and can be used as string keys; otherwise, some data may be lost or the result may not match expectations.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
