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

PHP provides an efficient list implementation in the form of the DS\Vector class. The DS\Vector class is a sequence of values stored in a contiguous buffer. The buffer can resize automatically depending on the number of elements. It is the most efficient sequential data structure because a value’s index is directly mapped to its index in the buffer. The size of DS\Vector is not bound by any factor or exponent and can be anything.

The push() function

The DS\Vector::push adds a value to the end of the vector.

Syntax

public Ds\Vector::push(mixed ...$values): void

Parameters

  • values: The values to be added.

Return value

The Ds\Vector::push does not return any values.

Code

Let’s run the following code to see what the output of push() function looks like.

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

In the code above, we create a new empty vector. Then, we use the push function to add values to the end of the vector.

You can push a single value to the vector using the following code.

$vector->push($value)

Additionally, the push() method supports adding multiple values or even a whole list of values to the vector.

To add multiple values, we simply pass each value separated by commas as the argument, as shown in the following code.

$vector->push([$value1, $value2)

You can also provide a list with the splat operator (...).

$vector->push(...[$valueList])

Finally, the print_r function is used to print the contents to the screen.

Copyright ©2024 Educative, Inc. All rights reserved