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 Build a Simple PHP Application Working With Functions Introducing Functions

array_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;

?>

This is what I did..

<?php

$numbers = array(1,5,8);

function array_sum($numbers); {

  return array_sum;

}


echo $numbers;

?>

Loads 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

Have 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.

Correct! this works! :) thanks!

Uff i was making the function...

function array_sum($numbers) { foreach($numbers as $number) { $sum = $sum + $number; } return $sum; }

But wasn't necessary.

That was it. I guess I was over thinking that answers. Thanks a lot!

Okay 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.

You 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.