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 trialEvan Osczepinski
5,189 Pointsarray_sum function challenge
I need some guidance please...
This is the question..
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.
<?php
$numbers = array(1,5,8);
$sum = 0;
foreach($numbers as $number) {
$sum = $sum + $number;
}
echo $sum;
?>
Richard Duncan
5,568 PointsLoads of errors in that code Evan Osczepinski you cannot redeclare a native function for one thing. The semi-colon after the function declaration and before the function body would also throw an error.
4 Answers
Richard Duncan
5,568 PointsHave you re-watched the video? You might be looking at it too hard something simple such as: -
$numbers = array(1,5,8);
echo array_sum($numbers);
may provide the answer you're looking for.
Sam Bass
9,038 PointsCorrect! this works! :) thanks!
Alan Mattanó
Courses Plus Student 12,188 PointsUff i was making the function...
function array_sum($numbers) {
foreach($numbers as $number) {
$sum = $sum + $number;
}
return $sum;
}
But wasn't necessary.
Evan Osczepinski
5,189 PointsThat was it. I guess I was over thinking that answers. Thanks a lot!
Evan Osczepinski
5,189 PointsOkay so the semi colon is fixed, however what do I declare if not the native function in this case then? I have watched the video 4 times and cannot wrap my head around this.
Richard Duncan
5,568 PointsYou don't need to declare a native function as it is predefined. You just need to call it and pass the parameters of the arguments it expects. So in this example array_sum provides the sum value of all objects in the array. Call the function and pass $numbers as the parameter and it will provide the same result (14) as the foreach loop used in the example.
Evan Osczepinski
5,189 PointsEvan Osczepinski
5,189 PointsThis is what I did..