PHP array_flip: Swapping Array Keys and Values
This article explains how the PHP function array_flip works, its parameter requirements, return values, edge cases such as duplicate values, and provides clear code examples demonstrating how to swap keys and values in an associative array.
The array_flip() function returns a new array where the original array's keys become values and its values become keys.
Values in the input array must be valid keys (integers or strings); otherwise a warning is issued and those pairs are omitted.
If a value appears multiple times, the last corresponding key is kept and earlier ones are discarded.
Parameter: trans – the array whose keys and values you want to exchange.
Return value: The flipped array on success, or NULL on failure.
Example 1:
<?php
$trans = array("a" => 1, "b" => 1, "c" => 2);
$flipped = array_flip($trans);
print_r($flipped);
?>Output:
Array
(
[1] => b
[2] => c
)Example 2 (demonstrating duplicate handling):
<?php
$trans = array("a" => 1, "b" => 1, "c" => 2);
$flipped = array_flip($trans);
print_r($flipped);
?>Output:
Array
(
[1] => b
[2] => c
)Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
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.