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 trial

PHP

functions code challenge

I've got the code to add some of the numbers, but I'm not sure how to go about getting all the numbers to add.

Here is the code:

    <?php

function mimic_array_sum($array) {
    foreach($array as $total) {
        $total = $total + $total;
    }
    return $total;
}
$var = array(1,2,3,4,5);
$total = mimic_array_sum($var);
echo $total;
?>

1 Answer

Paul Yorde

It's close. But in the foreach loop don't use $total as the temporary variable assigned to the items in the array. Use something like $number because if you use $total as your temporary variable it will reset every time you loop through the array items to the value of the next array item. This will not give you an accurate sum of the items in the array. Also you'll want to initialize the $total variable to 0 just before the foreach loop. This gives ensures that the value of $total starts with 0. Then you can replace one of the $total variables on the right side of your 'sum' equation with the $number variable. Everything else can stay the same.