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 trialJuliette Tworsey
Front End Web Development Techdegree Graduate 32,425 PointsStage 6- Working with functions
"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."
Anyone have any idea on how to approach this? I didn't find the preceding video to be of much guidance here. Thanks-
<?php
$numbers = array(1,5,8);
echo "sum(numbers) = " . array_sum($numbers) . "\n";
?>
1 Answer
Joe Cochran
18,249 PointsThis is a case where the challenge engine is being really picky. The challenge asks you to replace the loop with the array_sum() function. We start with:
<?php
$numbers = array(1,5,8);
$sum = 0;
foreach($numbers as $number) {
$sum = $sum + $number;
}
echo $sum;
?>
Then, as instructed, I will remove the loop entirely.
<?php
$numbers = array(1,5,8);
$sum = 0;
echo $sum;
?>
With this code, the easiest way to accomplish the task is to replace $sum = 0;
with array_sum(). I'll go ahead and add $sum = array_sum($numbers)
:
<?php
$numbers = array(1,5,8);
$sum = array_sum($numbers);
echo $sum;
?>
The good news is you were using the function correctly! Unfortunately, the challenge engine is checking the value of $sum at the end, whereas you were outputting the result of the array_sum() function directly.
Juliette Tworsey
Front End Web Development Techdegree Graduate 32,425 PointsJuliette Tworsey
Front End Web Development Techdegree Graduate 32,425 PointsOoooooooh! I get it now...thanks to you.
Thanks so much!
Anna Takang Nchongarrey-Oben
7,365 PointsAnna Takang Nchongarrey-Oben
7,365 PointsThanks a lot