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 trialPetru Popa
Courses Plus Student 1,092 Pointsstuck help please
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, replacing it with a call to the array_sum() function instead. Bummer! Cannot redeclare array_sum() in index.php on line 8 Preview Get Help Reset Code Recheck work index.php
<?php $numbers = array(1,5,8); $sum = 0; function array_sum($numbers){ array_sum($numbers); } echo $sum;
?> ā
<?php
$numbers = array(1,5,8);
$sum = 0;
function array_sum($numbers){
array_sum($numbers);
}
echo $sum;
?>
2 Answers
Romuald Le Bris
3,975 PointsHello Petru,
If I get it right, what you're trying to do is to echo the $sum value of the array $numbers. If so, you are using the good function but not in the good way.
You don't need to define array_sum like you do with the 'function' before it as it is a native php function.
You simply need to do this :
<?php
// You declare the array
$numbers = array(1,5,8);
// You echo the function you need with it's parameter.
// Here array_sum ask for an $array as parameter so we give our array $numbers
// And it will print the result in the same time which is 14.
echo array_sum($numbers);
//You can also keep the array_sum($numbers) result in a variable like you tried to do by doing this.
<?php
//I declare the array
$numbers = array(1,5,8);
// I declare the variable $sum with the function in it
$sum = array_sum($numbers);
// I print the value
echo $sum;
?>
Hope this will help you and if it does don't forget to +1 the answer so everyone who would meet the same issue can see it has been resolved ;)
Petru Popa
Courses Plus Student 1,092 PointsThanks,Romuald Le Bris.