Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php

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

Muhammad Ashir

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

DS\Vector::push

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

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

Code

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

Output

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

To run this program, you need to install Data Structures for PHP on your local machine.

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.

RELATED TAGS

php

CONTRIBUTOR

Muhammad Ashir
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring