Using PHP array_flip() to Reverse Array Keys and Values
This article explains how the PHP array_flip() function swaps an array's keys and values, shows its syntax, parameters, return values, and provides examples—including handling of duplicate values—to help developers correctly apply the function in backend code.
In PHP, the array_flip() function is commonly used to invert an array's keys and values, returning a new array where each original value becomes a key and each original key becomes its corresponding value.
Basic Syntax:
<code>array array_flip ( array $array )</code>Parameter:
The $array parameter is the array to be flipped.
Return Value:
The function returns the flipped array; if the argument is not a valid array, it returns bool(false) . Below is an example of using array_flip() :
<code>$array = array('a' => 'apple', 'b' => 'banana', 'c' => 'cherry');
$flippedArray = array_flip($array);
print_r($flippedArray);
</code>Output:
<code>Array
(
[apple] => a
[banana] => b
[cherry] => c
)
</code>If the original array contains duplicate values, only the last key will be kept in the flipped array, as demonstrated in the following example where two keys share the value “banana”:
<code>$array = array('a' => 'apple', 'b' => 'banana', 'c' => 'banana');
$flippedArray = array_flip($array);
print_r($flippedArray);
</code>Output:
<code>Array
(
[apple] => a
[banana] => c
)
</code>When using array_flip() , ensure that the original array's values are unique or can be used as unique string keys; otherwise the result may not be as expected.
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.