Mastering PHP’s array_flip: Reverse Keys and Values with Confidence
This guide explains PHP’s array_flip function, covering its syntax, parameters, return values, practical examples, and important caveats such as handling duplicate values to ensure reliable key‑value reversal in your code.
In PHP, the array_flip() function is a frequently used utility that swaps the keys and values of an array, returning a new array with the reversed mapping.
Basic Syntax
array array_flip ( array $array )Parameter Description
The sole parameter $array is the array you want to flip.
Return Value
The function returns the flipped array. If the supplied argument is not a valid array, it returns bool(false).
Example 1: Simple Flip
$array = array(
'a' => 'apple',
'b' => 'banana',
'c' => 'cherry'
);
$flippedArray = array_flip($array);
print_r($flippedArray);Output:
Array
(
[apple] => a
[banana] => b
[cherry] => c
)This example creates an associative array with three key‑value pairs, flips it, and prints the resulting array where the original values become keys.
Important Note on Duplicate Values
If the original array contains duplicate values, only the last occurrence is retained after flipping because keys must be unique. The earlier duplicates are overwritten.
Example 2: Duplicate Value Handling
$array = array(
'a' => 'apple',
'b' => 'banana',
'c' => 'banana'
);
$flippedArray = array_flip($array);
print_r($flippedArray);Output:
Array
(
[apple] => a
[banana] => c
)Here, the value banana appears twice. After flipping, only the last key ( 'c') is kept, demonstrating that duplicate values lead to data loss in the flipped array.
Final Caution
When using array_flip(), ensure that the original array’s values are unique or can serve as unique string keys; otherwise, the result may not match expectations.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
