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 trialMatthew Smart
12,567 PointsHelp please
Write the code inside this mimic_array_sum() function. That code should add up all individual numbers in the array and return the sum. You’ll need to use a foreach command to loop through the argument array, a working variable to keep the running total, and a return command to send the sum back to the main code.
do not understand this, can someone provide the correct code, and i will be able to see what it is i was meant to do.
1 Answer
Aaron Graham
18,033 PointsYou are supposed to write a function that will sum all the elements in an array. For example:
$myArray = array(1, 2, 3);
mimic_array_sum($myArray);
would give you 6.
To make the mimic_array_sum function, you need to make a function that takes one argument, an array, adds up all the elements in the array, and return the sum.
You can do it like this:
function mimic_array_sum($array) {
$sum = 0;
foreach($array as $item) {
$sum += $item;
};
return $sum;
};
The foreach will loop through the array that is passed into the function and add each element, one at a time, to the current sum. Once the foreach loop terminates, the sum is returned.