In computer science, a set is a data structure used to store unique elements. Similarly, PHP arrays can perform set-related operations such as intersection, union, and difference. This article focuses on how to perform array union operations in PHP.
PHP's built-in array_intersect() function retrieves the intersection of arrays. To get the union of multiple arrays, you can merge all arrays first and then remove duplicates. Here's an example:
function array_union(...$arrays) {
$result = [];
foreach ($arrays as $array) {
$result = array_merge($result, $array);
}
$result = array_unique($result);
return $result;
}
This function merges all input arrays and then removes duplicate values using array_unique(), producing the union of the arrays.
You can also achieve the union more concisely by combining PHP's variable-length arguments with array_merge() and array_unique():
function array_union(...$arrays) {
return array_unique(array_merge(...$arrays));
}
This approach also merges multiple arrays and removes duplicates with simple and readable code.
Here is an example demonstrating how to use the function to get the union of arrays:
$array1 = [1, 2, 3];
$array2 = [2, 3, 4];
$array3 = [3, 4, 5];
$result = array_union($array1, $array2, $array3);
print_r($result);
The output will be:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
This article demonstrated that PHP's array union can be easily implemented by merging arrays and removing duplicates. Whether using a custom function or PHP's built-in array_merge() and array_unique(), you can efficiently combine multiple arrays. Understanding and applying these functions effectively makes array operations simpler and more efficient.