Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Build a Simple PHP Application Working With Functions Introducing Functions

Fabrizio Rinaldi
Fabrizio Rinaldi
5,359 Points


Task: The code below creates an array of numbers, loops through them one at a time, and sums their values. PHP actually has a native function that does this same thing: array_sum(). [The array_sum() function receives an array as its one and only argument, and it sends back the sum as the return value.] Modify the code below: remove the foreach loop and the working sum variable, replacing them with a call to the array_sum() function instead.

Exercise: <?php

$numbers = array(1,5,8);

$sum = 0; foreach($numbers as $number) { $sum = $sum + $number; }

echo $sum;


I literally don't know where to start.

2 Answers

Ben Falk
Ben Falk
3,167 Points

First off, you would want to remove this line, as the instructions say:

$sum = 0; foreach($numbers as $number) { $sum = $sum + $number; }

Then, check the documentation to see how you would use the array_sum() function. http://php.net/manual/en/function.array-sum.php

Since you have an array of numbers already created, you should be able to echo out the results of array_sum(), using the $numbers array. Hope that helps you get started?

Carrie Lones
Carrie Lones
4,370 Points

So basically, the code that you're given, specifically the $sum variable and the foreach loop, work as a function in the sense that the $sum goes up when each $number is called, and you then echo out the $sum variable. What the code challenge is asking you to do is to replace that with the actual function array_sum().

Because the array_sum() function takes care of everything in the foreach loop, you don't need that at all, nor do you need the $sum variable which is solely used within that foreach loop. So you can get rid of the following:

$sum = 0;
$foreach($numbers as $number) {$sum = $sum + $number; }
echo $sum;

and add in the array_sum() function instead, calling up the variable that holds the array, and then you echo that out.