Master PHP’s array_flip(): Swap Keys and Values with Ease

This guide explains how PHP's array_flip() function swaps array keys and values, details its syntax, parameters, return behavior, and provides three practical code examples demonstrating usage with associative, fruit‑color, and numeric‑indexed arrays, including important caveats.

php Courses
php Courses
php Courses
Master PHP’s array_flip(): Swap Keys and Values with Ease

In PHP programming, arrays are a fundamental data structure, and the array_flip() function provides a convenient way to exchange an array's keys and values.

Function Purpose

The function takes an input array and returns a new array where each original value becomes a key and each original key becomes a value. If a value is not a string or integer, the function triggers an error.

Syntax

array array_flip ( array $array )

Parameters

$array

: The array whose keys and values you want to swap.

Return Value

The function returns the flipped array. Non‑string or non‑integer values in the original array cause a runtime error.

Examples

Example 1

$array = array("a" => 1, "b" => 2, "c" => 3);
$flippedArray = array_flip($array);
print_r($flippedArray);

Output:

Array
(
    [1] => a
    [2] => b
    [3] => c
)

This demonstrates swapping a simple associative array where numeric values become keys.

Example 2

$array = array("apple" => "red", "banana" => "yellow", "orange" => "orange", "grape" => "purple");
$flippedArray = array_flip($array);
print_r($flippedArray);

Output:

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

Here the fruit names are keys and their colors become values; after flipping, colors become keys.

Example 3

$array = array(1 => "a", 2 => "b", 3 => "c", 4 => "a");
$flippedArray = array_flip($array);
print_r($flippedArray);

Output:

Array
(
    [a] => 4
    [b] => 2
    [c] => 3
)

When duplicate values exist, the resulting array keeps the last key encountered for each value.

Conclusion

The array_flip() function is a practical tool for quickly swapping keys and values in PHP arrays, but it requires that original values be strings or integers to avoid errors.

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.

Arraysarray_flipkey-value swap
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.