Home > Article > Backend Development > How to merge arrays in php to remove duplicate data
In PHP, you can use the array_merge() and array_unique() functions to merge arrays and remove duplicate data. The syntax format is "array_unique(array_merge(array1,array2..))".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php merge arrays to remove duplicate data
<?php header("Content-type:text/html;charset=utf-8"); $arr1 = array( 'id' => 1234, 'url' => 'https://www.php.cn/', 'language' => 'PHP', 'article' => '数组排序函数', 6 => '345' ); $arr2 = array( 'id' => 5678, 6 => 34, 8 => 26, 11 => '345' ); echo '<pre class="brush:php;toolbar:false">'; $arr = array_merge($arr1, $arr2); echo '将 $arr1 与 $arr2 合并,结果为:'."<br>"; print_r($arr); $array = array_unique($arr); echo '去除重复数据'."<br>"; print_r($array); ?>
Output:
将 $arr1 与 $arr2 合并,结果为: Array ( [id] => 5678 [url] => https://www.php.cn/ [language] => PHP [article] => 数组排序函数 [0] => 345 [1] => 34 [2] => 26 [3] => 345 ) 去除重复数据 Array ( [id] => 5678 [url] => https://www.php.cn/ [language] => PHP [article] => 数组排序函数 [0] => 345 [1] => 34 [2] => 26 )
Description:
1, array_merge() function
array_merge() The function can merge the units of one or more arrays, that is, append the values in one array to the previous array, and return the merged array. The syntax format is as follows:
array_merge($array1 [, $array2 [, $array3 ...]])
Parameter$ array1, $array2,..., $arrayn are several arrays to be merged.
If the input array has the same string key name, the value after the key name will overwrite the previous value; if the array contains a numeric key name, the later value will not overwrite the previous value. Instead, they are appended; if the function has only one array parameter and the array is numerically indexed, the key names are re-indexed consecutively.
2. array_unique() function
array_unique -- remove duplicate values in the array
The syntax format is as follows:
array array_unique ( array array )
array_unique() accepts array Takes as input and returns a new array with no duplicate values
Note that the key names remain unchanged. array_unique() sorts the values first as strings, then retains only the first encountered key for each value, and then ignores all subsequent keys. This does not mean that the first occurrence of the same value in an unsorted array will be preserved.
Note: Two units are considered the same if and only if (string) $elem1 === (string) $elem2
. That is, when the expressions of the strings are the same. The first unit will be retained.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to merge arrays in php to remove duplicate data. For more information, please follow other related articles on the PHP Chinese website!