Using PHP’s array_flip() Function to Swap Keys and Values
This article explains PHP’s array_flip() function, showing its syntax, how it swaps array keys and values, handling duplicate values, and demonstrates practical uses with code examples that flip fruit and student arrays and retrieve values efficiently.
PHP provides a powerful function array_flip() that exchanges the keys and values of an array. This article introduces the function, its syntax, and practical usage through clear code examples.
The basic syntax of array_flip() is:
array array_flip ( array $array )The function 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 last key is retained while earlier duplicates are discarded.
Example 1 demonstrates flipping a fruit array:
<?php
$fruits = array(
"apple" => "red",
"orange" => "orange",
"banana" => "yellow"
);
$flipped_fruits = array_flip($fruits);
print_r($flipped_fruits);
?>The output is:
Array
(
[red] => apple
[orange] => orange
[yellow] => banana
)This shows that the original keys "apple", "orange", and "banana" have become the values "red", "orange", and "yellow" in the flipped array.
In real‑world code, array_flip() can be used to look up a key by its value. After flipping, you can use isset() to check for the existence of a specific value.
Example 2 flips a student‑age array to find a student by age:
<?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";
}
?>The script outputs:
The student with age 20 is JohnThis example shows how flipping the array allows direct retrieval of the student name from an age value.
Overall, mastering array_flip() enhances PHP array manipulation, enabling efficient key‑value swaps, duplicate handling, and lookup operations, 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.