Backend Development 4 min read

Understanding PHP's array_flip() Function: Usage, Syntax, and Examples

This article explains PHP's array_flip() function, detailing its purpose of swapping array keys and values, its syntax, parameter and return information, and provides three practical code examples illustrating its behavior with associative and indexed arrays.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Understanding PHP's array_flip() Function: Usage, Syntax, and Examples

In PHP programming, arrays are a common data structure, and the array_flip() function is a useful built‑in function that swaps array keys and values.

The function takes an array as its sole argument and returns a new array where the original keys become values and the original values become keys. The values must be strings or integers; otherwise an error occurs.

Syntax:

array array_flip ( array $array )

Parameter:

$array : the array whose keys and values are to be exchanged.

Return value:

The function returns the flipped array. If any value in the input array is not a string or integer, a warning is raised.

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
)

Example 2 demonstrates flipping an associative array where keys are fruit names and values are colors.

$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
)

Example 3 shows flipping a numerically indexed array with duplicate values; the resulting array keeps the last index for each value.

$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
)

In summary, array_flip() is a practical PHP function for swapping keys and values of an array, useful especially with associative arrays, provided that all values are strings or integers.

backendProgrammingphpArrayarray_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.