Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP Build a Simple PHP Application Working With Functions Introducing Functions

Juliette Tworsey
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Juliette Tworsey
Front End Web Development Techdegree Graduate 32,413 Points

Stage 6- Working with functions

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

Anyone have any idea on how to approach this? I didn't find the preceding video to be of much guidance here. Thanks-

sum.php
<?php

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

echo "sum(numbers) = " . array_sum($numbers) . "\n";


?>

1 Answer

This is a case where the challenge engine is being really picky. The challenge asks you to replace the loop with the array_sum() function. We start with:

<?php

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

$sum = 0;
foreach($numbers as $number) {
    $sum = $sum + $number;
}

echo $sum;

?>

Then, as instructed, I will remove the loop entirely.

<?php

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

$sum = 0;

echo $sum;

?>

With this code, the easiest way to accomplish the task is to replace $sum = 0; with array_sum(). I'll go ahead and add $sum = array_sum($numbers):

<?php

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

$sum = array_sum($numbers);

echo $sum;

?>

The good news is you were using the function correctly! Unfortunately, the challenge engine is checking the value of $sum at the end, whereas you were outputting the result of the array_sum() function directly.