Home > Article > Backend Development > How to find the union of arrays in php
Method to find the union of arrays: 1. Use array_merge() to merge multiple arrays into one array, the syntax is "array_merge(array1, array2...)"; 2. Use "array_values(array_unique) (Merge Arrays))" removes duplicate values from the merged arrays and reorders them.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
What is a union?
Given two sets A and B, the set formed by merging all their elements together is called the union of set A and set B.
What is array union?
Simply put, it is a set that combines two or more arrays to remove duplicates.
php method to find the union of arrays
1. Merge arrays
In PHP, the array_merge() function is used To merge multiple arrays into one
array_merge() function will merge the elements of multiple arrays, and the elements of the next array will be appended to the previous array, and finally return the merged array.
If the original array has the same string key name, then the value after the key name will overwrite the previous value; if the original array contains a numeric key name, then the subsequent value will not Overwrites the previous value and appends it instead.
<?php header("Content-type:text/html;charset=utf-8"); $arr1 = [1,2,3,4,5]; $arr2 = [2,3,6,7,8,9]; var_dump($arr1); var_dump($arr2); $result = array_merge($arr1,$arr2); var_dump($result); ?>
2. Remove duplicate values and reorder
array_unique() function can Remove duplicate values from an array
array_values() function can reorder
<?php header("Content-type:text/html;charset=utf-8"); $arr1 = [1,2,3,4,5]; $arr2 = [2,3,6,7,8,9]; $result = array_merge($arr1,$arr2); var_dump($result); $res=array_values(array_unique($result)); var_dump($res); ?>
Recommended study:《PHP video tutorial》
The above is the detailed content of How to find the union of arrays in php. For more information, please follow other related articles on the PHP Chinese website!