Open In App
Related Articles

PHP | Ds\Sequence reduce() Function

Improve Article
Improve
Save Article
Save
Like Article
Like

The Ds\Sequence::reduce() function is an inbuilt function in PHP which is used to reduce the sequence to a single value using a callback function.

Syntax:

mixed abstract public Ds\Sequence::reduce ( callable $callback 
[, mixed $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 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 of callback function.

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

Program 1:




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


Output:

Sequence 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 sequence
$seq = new \Ds\Vector([10, 20, 30, 40, 50]); 
  
echo("Original sequence elements\n"); 
  
print_r($seq); 
  
$func_gfg = function($carry, $element) { 
    return $carry * $element
}; 
  
echo("\nSequence after reducing to single element\n"); 
  
// Use reduce() function 
var_dump($seq->reduce($func_gfg, 10)); 
  
?> 


Output:

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

Sequence after reducing to single element
int(120000000)

Reference: https://www.php.net/manual/en/ds-sequence.reduce.php


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 22 Aug, 2019
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials