Using PHP array_flip() to Reverse Array Keys and Values

This article explains how the PHP array_flip() function swaps an array's keys and values, shows its syntax, parameters, return values, and provides examples—including handling of duplicate values—to help developers correctly apply the function in backend code.

php Courses
php Courses
php Courses
Using PHP array_flip() to Reverse Array Keys and Values

In PHP, the array_flip() function is commonly used to invert an array's keys and values, returning a new array where each original value becomes a key and each original key becomes its corresponding value.

Basic Syntax:

array array_flip ( array $array )

Parameter:

The $array parameter is the array to be flipped.

Return Value:

The function returns the flipped array; if the argument is not a valid array, it returns bool(false). Below is an example of using array_flip():

$array = array('a' => 'apple', 'b' => 'banana', 'c' => 'cherry');
$flippedArray = array_flip($array);
print_r($flippedArray);

Output:

Array
(
    [apple] => a
    [banana] => b
    [cherry] => c
)

If the original array contains duplicate values, only the last key will be kept in the flipped array, as demonstrated in the following example where two keys share the value “banana”:

$array = array('a' => 'apple', 'b' => 'banana', 'c' => 'banana');
$flippedArray = array_flip($array);
print_r($flippedArray);

Output:

Array
(
    [apple] => a
    [banana] => c
)

When using array_flip(), ensure that the original array's values are unique or can be used as unique string keys; otherwise the result may not be as expected.

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.

php-functionsarray manipulationarray_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.