This article mainly introduces to you the detailed explanation of PHP's specific method of deleting duplicate elements in an array.
PHP performs basic operations such as deleting, querying, and adding elements in an array. It can be said that it is a relatively common question in PHP interview questions. I believe that for most PHP scholars, these are very simple knowledge points. But for novices, it may not be clear.
Below we will introduce in detail two methods of deleting duplicate elements from PHP arrays through simple code examples.
Method 1: Remove array duplication through the array_unique function
<?php $arr = ['1', '1', 'PHP', 'PHP', 2, 3]; print_r($arr); echo "<br>"; print_r(array_unique($arr));
Here we define an array $arr, and you can find that there are 2 duplicate elements in the array , and then use the array_unique function to remove duplicate elements.
Accessed through the browser, the return value result is as shown below:
From the picture we can find that the repeated elements in the original array have been removed through the array_unique function Delete it, and keep the remaining key names unchanged.
array_unique: Remove duplicate values in the array
Note: Key names are retained constant.
Method 2: Remove array duplication through the array_flip function
<?php $arr = ['1', '1', 'PHP', 'PHP', 2, 3]; print_r($arr); echo "<br>"; print_r(array_unique($arr)); echo "
"; print_r(array_flip($arr));
Here we combine the array_unique method for comparison. The test results are as follows:
As shown in the figure, the array_flip function can also be used to deduplicate the array, but unlike array_unique, the array_flip function method causes the key names to be exchanged after deduplication.
array_flip: Exchange the keys and values in the array
Note: If the same value appears multiple times times, the last key name will be used as its value, and the other keys will be discarded.
This article is about two methods of PHP deleting duplicate elements in arrays. I hope it will be helpful to friends in need!
If you want to learn more about PHP, you can follow the PHP Chinese website PHP Video Tutorial, everyone is welcome to refer to and learn!
The above is the detailed content of How to remove duplicate elements from an array in PHP? (Pictures + Videos). For more information, please follow other related articles on the PHP Chinese website!