Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

html
css
php
web development
communitycreator

What is the Ds\Set reduce() function in PHP?

Saad Akbar

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 functions

PHP has more than a thousand inbuilt functions and enables its developers to create their own functions as well. Functions are considered one of the extraordinary strengths of PHP; they are a structure of code that can be used repetitively. They need to be called in order to achieve their specific task.

How to create a function in PHP

Below, we see how to create a function, callEducative(), which prints Welcome to Educative!.

<?php
function callEducative() {
  echo "Welcome to Educative!";
}

callEducative(); // function call
?>

Ds\Set reduce() function

This is an inbuilt function that applies operation using the callback function to reduce the set to a single value.

mixed public Ds\Set::reduce ( callable $callback 
[, mixed $initial ] )

Code Example

The following code shows the implementation reduce() function:

<?php 
  

$set = new \Ds\Set([10, 15, 25, 35, 40]); 
  
echo("Initial elements of the set\n"); 
  
print_r($set); 
  
$f = function($carry, $element) { 
    return $carry * $element; 
}; 
  
echo("\nReduced to a single element\n"); 
  
// reduce() 
var_dump($set->reduce($f, 10)); 
  
?> 

Output

Initial elements of the set
Ds\Set Object
{
    [0] => 10
    [1] => 15
    [2] => 25
    [3] => 35
    [4] => 40
    
}

Reduced to a single element
int(5250000)

RELATED TAGS

html
css
php
web development
communitycreator

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