Backend Development 5 min read

Using PHP's array_flip() Function to Swap Keys and Values

This article explains PHP's array_flip() function, showing its syntax, behavior with duplicate values, and practical examples that demonstrate how to exchange array keys and values and apply the function for look‑ups and data manipulation.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP's array_flip() Function to Swap Keys and Values

PHP is a widely used server‑side scripting language that provides powerful functions for handling arrays and data. One particularly useful function is array_flip() , which swaps the keys and values of an array.

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 and earlier duplicates are discarded.

Below is a simple example that demonstrates the usage of array_flip() :

<?php
$fruits = array("apple" => "red", "orange" => "orange", "banana" => "yellow");

$flipped_fruits = array_flip($fruits);

print_r($flipped_fruits);
?>

The output of the above code is:

Array
(
    [red] => apple
    [orange] => orange
    [yellow] => banana
)

In this example, the associative array $fruits contains three elements. After applying array_flip() , the keys and values are exchanged and stored in $flipped_fruits , which is then printed with print_r() .

Another practical scenario is using array_flip() to look up a key by its value. By flipping the array first and then using isset() , you can check whether a specific value exists as a key in the flipped array.

<?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 John

Here, the associative array $students maps student names to ages. After flipping, the ages become keys, allowing a quick lookup of the student name for a given age.

Overall, array_flip() is a powerful PHP function that simplifies operations such as key‑value look‑ups, removing duplicate values, and improving code readability and efficiency when handling array data.

backendPHPdata-manipulationphp-arrayarray_flip
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.