PHP array_flip() function
The array_flip()
function in PHP is used to exchange the keys and values of an array. This means that the values in the original array become the keys in the resulting array, and the keys from the original array become the values. If a value occurs more than once in the input array, only the last value is used as a key, and previous duplicates are overwritten.
Syntax:
Parameters:
- $array: The input array. The array must have values that are either integers or strings because they will become the keys of the new array.
Return Value:
- The function returns a new array with the keys and values flipped. If a value in the original array is not suitable to be used as a key (e.g., it's an array or object), the function will throw a warning and skip that element.
Example 1: Basic Usage
Output:
In this example, the original array's values (e.g., "red"
, "yellow"
, "purple"
) become the keys, and the original keys (e.g., "apple"
, "banana"
, "grape"
) become the values.
Example 2: Duplicate Values
If the original array contains duplicate values, array_flip()
will only retain the last occurrence, as keys must be unique in PHP arrays.
Output:
Here, both "a"
and "c"
have the value 1
. After flipping, only the last key ("c"
) associated with the value 1
is retained.
Example 3: Handling Invalid Keys
If the values in the array are not suitable to be keys (e.g., arrays, objects, or null
), array_flip()
will skip those elements and issue a warning.
Output:
In this case, the value null
and the array [1, 2, 3]
are skipped because they cannot be used as array keys. The function only flips the element with a valid key-value pair ("a" => 100
).
Practical Usage:
array_flip()
is useful for:- Reversing the mapping of keys and values in associative arrays.
- Quickly searching for keys by their values after flipping.
- Transforming arrays when values need to be unique and suitable for use as keys.
Limitations:
- Values that are not strings or integers (e.g., arrays, objects) cannot be used as keys and will be skipped.
- If multiple values in the original array are the same, only the last one is kept as a key after flipping, which may lead to data loss if duplicates exist.
Summary:
array_flip($array)
exchanges the keys and values in the input array.- The function returns a new array where the original values become the keys and the original keys become the values.
- It’s useful for situations where you need to reverse the key-value relationship of an array, but be cautious with duplicate values and non-keyable data types.