Master 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.
Overview
The array_flip() function in PHP swaps the keys and values of an array, returning a new array with the inverted mapping. It is a frequently used utility for transforming associative arrays.
Syntax
array array_flip ( array $array )Parameter
$array– The input array whose keys and values you want to reverse.
Return Value
The function returns the flipped array. If the supplied argument is not a valid array, it returns bool(false).
Basic Example
$array = array(
'a' => 'apple',
'b' => 'banana',
'c' => 'cherry'
);
$flippedArray = array_flip($array);
print_r($flippedArray);Output:
Array
(
[apple] => a
[banana] => b
[cherry] => c
)Handling Duplicate Values
If the original array contains duplicate values, only the last key for each duplicated value is retained after flipping, because array keys must be unique.
$array = array(
'a' => 'apple',
'b' => 'banana',
'c' => 'banana'
);
$flippedArray = array_flip($array);
print_r($flippedArray);Output:
Array
(
[apple] => a
[banana] => c
)Important Caveat
When using array_flip(), ensure that the original array’s values are unique and can be used as string keys; otherwise, later entries will overwrite earlier ones, leading to unexpected results.
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.
