In PHP array operations, array_flip() and array_values() are two very powerful functions. When you are dealing with arrays that are confusing, irregular, or need to be reconstructed, the combination of these two functions can bring unexpected efficiency gains.
This article will introduce how to use these two functions in combination to quickly reconstruct the structure and format of PHP arrays.
The purpose of array_flip() is to swap the keys and values of the array . This is very useful in some scenarios where keys need to be found by values.
$input = ['a' => 'apple', 'b' => 'banana'];
$result = array_flip($input);
// result: ['apple' => 'a', 'banana' => 'b']
Note: If the value of the array is not unique, array_flip() will override the key corresponding to the duplicate value.
array_values() is to rebuild the index array and renumber the value of the array as the index key starting from 0.
$input = ['first' => 'apple', 'second' => 'banana'];
$result = array_values($input);
// result: ['apple', 'banana']
When we need to deduplicate, rearrange indexes and standardize array formats , it will be very convenient to combine array_flip() and array_values() .
Suppose you receive an array of tags from the user form:
$tags = ['php', 'html', 'css', 'php', 'javascript', 'html'];
You hope:
Remove duplicates
Reorder key values to increment from 0
You can do this:
$uniqueTags = array_values(array_flip(array_flip($tags)));
The first array_flip($tags) : Use the tag as a key to remove duplicate values.
The second array_flip(...) : restores the original "value", but has been deduplicated.
The last array_values(...) : Reconstruct the key to a numeric index.
Final result:
['php', 'html', 'css', 'javascript']
Clean, deduplication, neat indexing!
Suppose you are receiving an array of options from the URL parameter, for example:
https://m66.net/filter.php?tags[]=php&tags[]=php&tags[]=mysql&tags[]=laravel
The processing code is as follows:
$tags = $_GET['tags'] ?? [];
$cleanTags = array_values(array_flip(array_flip($tags)));
This ensures that your $cleanTags variable contains deduplication tags and is in a standard index array.
Using array_flip() can cleverly utilize the uniqueness of keys to achieve deduplication;
Then use array_values() to restore it to a clean index array;
Used in combination, it is very efficient in handling duplicate data and formatting array structures;
Especially suitable for use in scenarios such as processing user input, configuration options, label data, etc.
The combination of these two functions not only makes your code more concise, but also reduces dependence on functions such as foreach or in_array() , improving performance and readability.