Thursday, November 20, 2025
HomeLanguagesPHP | DsVector reduce() Function

PHP | Ds\Vector reduce() Function

The Ds\Vector::reduce() function is an inbuilt function in PHP which reduce the vector to a single value by applying operations in the callback function.

Syntax:

mixed  public Ds\Vector::reduce( $callback, $initial )

Parameters: This function accepts two parameters as mentioned above and described below:

  • $callback: This parameter holds the function which contains the operation on the elements and store carry. This callback function contains two arguments, carry and value, where carry is the value returned by the function and value is the value of the element at the current iteration.
  • $initial: This parameter holds the initial value of carry, which can be NULL.

Return Value: This function returns the final value returned by the callback function.

Below programs illustrate the Ds\Vector::reduce() function in PHP:

Program 1:




<?php
  
// Declare new Vector
$vect = new \Ds\Vector([1, 2, 3, 4, 5]);
  
echo("Vector Elements\n");
  
print_r($vect);
  
// callback function with reduce function
echo("\nElement after performing operation\n");
var_dump($vect->reduce(function($carry, $element) {
    return $carry + $element + 2;
}));
  
?>


Output:

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

Element after performing operation
int(25)

Program 2:




<?php
  
// Declare new Vector
$vect = new \Ds\Vector([10, 20, 30, 40, 50]);
  
echo("Original vector elements\n");
  
print_r($vect);
  
$func_gfg = function($carry, $element) {
    return $carry * $element;
};
  
echo("\nVector after reducing to single element\n");
  
// Use reduce() function
var_dump($vect->reduce($func_gfg, 10));
  
?>


Output:

Original vector elements
Ds\Vector Object
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
)

Vector after reducing to single element
int(120000000)

Reference: http://php.net/manual/en/ds-vector.reduce.php

RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32404 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6775 POSTS0 COMMENTS
Nicole Veronica
11924 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11994 POSTS0 COMMENTS
Shaida Kate Naidoo
6903 POSTS0 COMMENTS
Ted Musemwa
7159 POSTS0 COMMENTS
Thapelo Manthata
6859 POSTS0 COMMENTS
Umr Jansen
6846 POSTS0 COMMENTS