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 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. 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 John Through 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendArraysphp-functionsarray_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

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.