What is the Ds\Vector merge() function in PHP?

Overview

The Vector class in PHP is an array that is automatically resized. The elements of a Vector instance are accessible via indexes.

This shot discusses the merge method of the Vector class.

Description

The merge method combines the Vector instance it is called on with the elements inside $values to produce a new Vector that is then returned.

Note: The elements of $values come after the elements of the current instance of the Vector on which the merge method is invoked.

Syntax

<?php
public Ds\Vector::merge(mixed $values): Ds\Vector
?>

Parameters

  • $values is an object that is traversable, meaning an object that implements Traversable interface (e.g. Vector); it can be an array as well.

Return value

  • A Vector that contains the elements of the current instance and elements of $values is returned.

Exceptions

None.

Example

<?php
$vec = new \Ds\Vector([1, 2, 3]);
$arr = [4, 5, 6];
print_r($vec->merge($arr));
print_r($vec);
?>

Output:

Ds\Vector Object
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
Ds\Vector Object
(
[0] => 1
[1] => 2
[2] => 3
)

In the example above, a vector $vec is initialized with the values 1, 2, and 3. An array $arr is initialized with the values 4, 5, and 6. The merge method is invoked on $vec with the $values argument containing the array $arr. This results in the merge method call returning a Vector that contains elements of both $vec and $arr.

Note: $vec itself remains unchanged.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved