Home >Backend Development >PHP Problem >How to exclude duplicate arrays in PHP
How to exclude duplicate arrays in PHP: 1. Create a PHP sample file; 2. Define the array to be deduplicated as "$oldArr" and the new array after deduplication as "$newArr"; 3. Use the "array_unique()" function to remove duplicate elements in the array and return the deduplicated array. The code is "$newArr = array_unique($oldArr);" to eliminate it; 4. You can also use a for loop to remove it. Heavy.
Operating system for this tutorial: Windows 10 system, PHP version 8.1.3, Dell G3 computer
How to exclude duplicate arrays in PHP
1. Use the array_unique function
The array_unique() function is a function provided by PHP for deduplication. Its function is to remove duplications in the array. elements and return the deduplicated array.
The sample code is as follows:
<?php $oldArr = array("apple", "orange", "banana", "apple", "banana"); $newArr = array_unique($oldArr); print_r($newArr); ?>
The output result is:
Array ( [0] => apple [1] => orange [2] => banana )
In the above example, $oldArr is the array to be deduplicated, and $newArr is the new array after deduplication. . After deduplication through the array_unique() function, the output result is an array of three elements, namely "apple", "orange" and "banana".
2. Use the loop method
In addition to using the array_unique() function, you can also remove duplicates through a loop. The specific implementation idea is: traverse each element in the array, and compare the traversed element with all subsequent elements. If a duplicate element appears later, delete the element from the original array.
The sample code is as follows:
<?php $oldArr = array("apple", "orange", "banana", "apple", "banana"); for($i=0; $i<count($oldArr)-1; $i++){ for($j=$i+1; $j<count($oldArr); $j++){ if($oldArr[$i] == $oldArr[$j]){ array_splice($oldArr, $j, 1); $j--; } } } print_r($oldArr); ?>
The output result is:
Array ( [0] => apple [1] => orange [2] => banana )
In the above example, $oldArr is the array to be deduplicated. Each element in the array is traversed through a double loop, and the following elements are compared in turn to see if they are duplicates. If there are duplicates, delete them until the deletion is complete and the array is output.
Summary
This article introduces two PHP methods for removing duplicate data from arrays, namely the array_unique() function and the loop method. The specific method to use depends on the actual needs. It is recommended to choose the appropriate method according to the actual situation. At the same time, you also need to pay attention to the relevant knowledge and skills of PHP array deduplication to improve development efficiency and code quality as much as possible.
The above is the detailed content of How to exclude duplicate arrays in PHP. For more information, please follow other related articles on the PHP Chinese website!