Friday, October 17, 2025
HomeLanguagesPHP | DsMap union() Function

PHP | Ds\Map union() Function

The Ds\Map::union() function is an inbuilt function in PHP which is used to create a new map which contains the union of two maps.

Syntax:

Ds\Map Ds\Map::union( $map )

Parameters: This function accepts single parameter $map which is used to hold the other map of the instance to combine with the current instance.

Return Value: It returns a map which contains the union of two maps.

Below programs illustrate the Ds\Map::union() function in PHP:

Program 1:




<?php 
  
// Declare a new map
$a = new \Ds\Map(["a" => 1, "b" => 3, "c" => 5]); 
  
// Declare another new map
$b = new \Ds\Map(["a" => 2, "c" => 3, "d" => 6]); 
  
// Print the Union of two map
echo("Union of both map is: \n"); 
  
print_r($a->union($b));
  
?>


Output:

Union of both map is: 
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 2
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 3
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

    [3] => Ds\Pair Object
        (
            [key] => d
            [value] => 6
        )

)

Program 2:




<?php 
  
// Declare a new map
$a = new \Ds\Map(["a" => "Geeks", "b" => "for", "c" => "Geeks"]); 
  
// Declare another new map
$b = new \Ds\Map(["b" => "Computer", "e" => "Science", "f" => "Portal"]); 
  
// Print the union of two map
echo("Union of both map is: \n"); 
  
print_r($a->union($b));
  
?>


Output:

Union of both map is: 
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => Geeks
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => Computer
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => Geeks
        )

    [3] => Ds\Pair Object
        (
            [key] => e
            [value] => Science
        )

    [4] => Ds\Pair Object
        (
            [key] => f
            [value] => Portal
        )

)

Reference: https://www.php.net/manual/en/ds-map.union.php

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS