Backend Development 2 min read

PHP array_flip: Swapping Array Keys and Values

This article explains how the PHP function array_flip works, its parameter requirements, return values, edge cases such as duplicate values, and provides clear code examples demonstrating how to swap keys and values in an associative array.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP array_flip: Swapping Array Keys and Values

The array_flip() function returns a new array where the original array's keys become values and its values become keys.

Values in the input array must be valid keys (integers or strings); otherwise a warning is issued and those pairs are omitted.

If a value appears multiple times, the last corresponding key is kept and earlier ones are discarded.

Parameter: trans – the array whose keys and values you want to exchange.

Return value: The flipped array on success, or NULL on failure.

Example 1:

<?php
$trans = array("a" => 1, "b" => 1, "c" => 2);
$flipped = array_flip($trans);
print_r($flipped);
?>

Output:

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

Example 2 (demonstrating duplicate handling):

<?php
$trans = array("a" => 1, "b" => 1, "c" => 2);
$flipped = array_flip($trans);
print_r($flipped);
?>

Output:

Array
(
    [1] => b
    [2] => c
)
backendPHPTutorialphp-functionsarray-manipulationarray_flip
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

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.