Master PHP’s array_flip: Swap Keys and Values with Easy Examples
Learn how PHP’s array_flip function swaps array keys and values, understand its syntax, handle duplicate values, and see practical code examples that demonstrate finding keys by value and improving data handling efficiency in your backend projects.
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.
Basic Syntax
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 and earlier ones are discarded.
Simple Example
<?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
)Practical Use Case: Finding a Key by Value
When you need to locate a key based on its value, you can first flip the array and then use isset() to check for the desired 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";
}
?>The script outputs:
The student with age 20 is JohnConclusion
The array_flip() function is a powerful tool in PHP for swapping array keys and values, enabling efficient lookups, removal of duplicate values, and cleaner code in backend development.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
