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 trialNaison Masiyashe
2,736 Pointsi am stuck here,i am mixing the code
how do i replace the foreach with a array_sum function
<?php
$numbers = array(1,5,8);
$numbers = array_sum(array$numbers);
echo "sum(a) = " . array_sum($a) . "\n";
$sum = 0;
foreach($numbers as $number) {
$sum = $sum + $number;
}
echo $sum;
?>
1 Answer
Jennifer Nordell
Treehouse TeacherArray_sum is a built in function in php. It's nothing you have to code yourself. And the challenge explicitly states that you need to remove the for loop. The array_sum function does exactly what that for loop is currently doing. What we want to do is to call the fucntion array_sum, pass it in our array, put that value into the $sum variable, and then echo out the result. Take a look at what you need:
<?php
$numbers = array(1,5,8);
$sum = 0;
$sum = array_sum($numbers);
echo $sum;
?>
Naison Masiyashe
2,736 PointsNaison Masiyashe
2,736 Pointsthank you Jennifer,i was lost there