Using PHP's array_flip() Function to Swap Keys and Values
This article explains PHP's array_flip() function, detailing its syntax, behavior with duplicate values, and practical uses such as reversing associative arrays and looking up keys by value, illustrated with clear code examples and output demonstrations.
PHP is a widely used server‑side scripting language that provides powerful functions for handling arrays. One particularly useful function is array_flip() , which swaps the keys and values of an array.
The basic syntax of the function is:
array array_flip ( array $array )It accepts an array and returns a new array where the original keys become values and the original values become keys. If duplicate values exist, the function keeps the last key and discards earlier ones.
Example 1 demonstrates flipping a simple associative array of fruits:
<?php
$fruits = array(
"apple" => "red",
"orange" => "orange",
"banana" => "yellow"
);
$flipped_fruits = array_flip($fruits);
print_r($flipped_fruits);
?>The output shows that the colors become keys and the fruit names become values:
Array
(
[red] => apple
[orange] => orange
[yellow] => banana
)A practical application is searching for a key by its value. By flipping the array first, you can use isset() to check for the existence of a value:
<?php
$students = array(
"Tom" => 18,
"John" => 20,
"Mary" => 19
);
$flipped_students = array_flip($students);
$age_to_find = 20;
if (isset($flipped_students[$age_to_find])) {
$student_name = $flipped_students[$age_to_find];
echo "The student with age $age_to_find is $student_name";
} else {
echo "No student with age $age_to_find";
}
?>This code outputs:
The student with age 20 is JohnThrough these examples, the article shows that array_flip() is a powerful tool for array manipulation in PHP, enabling tasks such as key‑value reversal, duplicate handling, and efficient look‑ups, thereby improving code readability and performance.
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.