From the course: Functional Programming with PHP

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Solution: Tallying votes

Solution: Tallying votes - PHP Tutorial

From the course: Functional Programming with PHP

Start my 1-month free trial

Solution: Tallying votes

(upbeat music) - [Narrator] Okay so it's time to take a look at the solution of how to implement our tally votes function. This is the way that I did it. What I did was use array reduce, so I said return array reduce, and I called reduce on our votes argument with a starting value of an empty array. Now, the accumulator function here was definitely the trickiest part. So here's what I did, I defined a function that takes two arguments, carry and vote. And what I did was use array merge with the first argument being carry which contained the votes that we had accumulated so far. And then I merged that with an array where the key is the vote or the current name that we're looking at, and the value of that key would depend on whether or not there was already an entry for that name. So what I did was use a ternary operator with the condition that array key exists and I wanted to see if the array that we'd…

Contents