Home>Article>Backend Development> How to perform union sum in php array
Implementation steps: 1. Use array_merge() to merge multiple arrays into one array, the syntax is "array_merge(array 1, array 2...)"; 2. Use array_unique() to remove the elements in the merged array For repeated values, the syntax "array_unique (merge array)" will return a union array; 3. Use the array_sum() function to calculate the sum of the union arrays, the syntax "array_sum (union array)".
The operating environment of this tutorial: windows7 system, PHP8.1 version, DELL G3 computer
Array union is to combine two or more The collection after array merging and deduplication.
In PHP arrays, you can use the array_merge() function, array_unique() function and array_sum() function to perform union summation.
Implementation idea:
First merge the arrays and find the union of two or more arrays
Then sum the unions
Implementation steps:
Step 1 : Use the array_merge() function to merge arrays
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.
Note: 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 later value will The previous value is not overwritten, but appended to it.
Example: Merge 3 arrays
Step 2: Use the array_unique() function to remove duplicate values from the merged array to obtain the array Union
array_unique() function can remove duplicate values from the array
$bj=array_unique($result); echo "并集数组:"; var_dump($bj);
Step 3: Use array_sum() function to calculate the union The sum of arrays
array_sum() function can calculate the sum of all elements in an array.
$sum=array_sum($bj); echo "并集之和:".$sum;
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to perform union sum in php array. For more information, please follow other related articles on the PHP Chinese website!