How to Use array_flip in PHP: Syntax and Examples
In PHP,
array_flip swaps the keys and values of an array, turning values into keys and keys into values. Use it by passing your array to array_flip($array), which returns the flipped array.Syntax
The array_flip function takes one parameter: the array you want to flip. It returns a new array where the original values become keys, and the original keys become values.
array_flip(array $array): array- $array: The input array to flip.
Note: Values in the original array must be valid keys (strings or integers). If values are duplicated, the last key will be used.
php
<?php array_flip(array $array): array; ?>
Example
This example shows how array_flip swaps keys and values in a simple array.
php
<?php $original = ['apple' => 'red', 'banana' => 'yellow', 'grape' => 'purple']; $flipped = array_flip($original); print_r($flipped); ?>
Output
Array
(
[red] => apple
[yellow] => banana
[purple] => grape
)
Common Pitfalls
Common mistakes when using array_flip include:
- Using arrays with duplicate values: only the last key for a duplicated value is kept.
- Using values that are not strings or integers: these cannot become keys and will be ignored.
- Expecting the original array to be modified:
array_flipreturns a new array and does not change the original.
php
<?php // Duplicate values example $input = ['a' => 1, 'b' => 1, 'c' => 2]; $flipped = array_flip($input); print_r($flipped); // Output shows only last key for duplicate value 1 ?>
Output
Array
(
[1] => b
[2] => c
)
Quick Reference
| Function | Description |
|---|---|
| array_flip($array) | Returns a new array with keys and values swapped |
| Input values | Must be strings or integers to become keys |
| Duplicate values | Last key for duplicate value is used |
| Original array | Not modified by array_flip |
Key Takeaways
Use array_flip to swap keys and values in an array easily.
Input values must be strings or integers to become valid keys.
If values repeat, only the last key is preserved in the flipped array.
array_flip returns a new array and does not change the original.
Check your array for duplicates to avoid unexpected results.