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 demonstrating practical examples such as swapping keys and values in associative arrays and using the flipped array for lookups, while highlighting its benefits for code simplicity and efficiency.
PHP is a widely used server‑side scripting language that provides powerful functions for handling arrays; one of them is array_flip() , which swaps the keys and values of an array.
The basic syntax is array array_flip ( array $array ) , which returns a new array where original keys become values and original values become keys. If duplicate values exist, the last key is kept.
Example 1 demonstrates flipping a fruit‑color associative array:
"red", "orange" => "orange", "banana" => "yellow");
$flipped_fruits = array_flip($fruits);
print_r($flipped_fruits);
?>The output shows red => apple , orange => orange , and yellow => banana , confirming the key‑value exchange.
Example 2 shows a practical lookup scenario: after flipping a student‑age array, isset() can be used to find a name by age.
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 script outputs “The student with age 20 is John”, illustrating how array_flip() enables reverse lookups.
In real development, array_flip() is useful for tasks such as searching for keys by value, removing duplicate values, and simplifying code, thereby improving efficiency and readability.
In summary, mastering array_flip() helps PHP developers handle associative arrays more effectively.
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.