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 Basic PHP Website (2018) Listing and Sorting Inventory Items Introducing Functions

Can someone explain this since it's impossible to search this challenge in the treehouse community.

Treehouse link the challenges and quizes to the community instead of us having to search through the whole community. Soap box over.

Brain fart on what to do here.


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

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

echo $sum;


3 Answers

Matthew Smart
Matthew Smart
12,567 Points

What is your question? You want us to explain how the code above works?

  1. You're creating an array to hold the values 1,5 and 8.
  2. Create $sum variable ready for use in the foreach loop
  3. Foreach( $numbers as $number ) is saying that for every number inside the array.
  4. inside the loop you are saying:

       $sum = $sum + $number;     //$sum is equal to 0.

So as you go through each number it is saying add those numbers together.

1st loop    $sum = $sum + $number   //  0   =   0   +  1    
2nd loop  $sum = $sum + $number   //  1   =   1   +  5
3rd loop   $sum = $sum + $number   //  6   =   6   +  8

As you can see each loop the $sum variable has added a number from the array to itself.

Once the loop ends as there isn't any values left in the array, you are using echo $sum. This means print out to the page whatever value the variable $sum holds.

Hey.. You need to modify the code so it uses the "array_sum" method.. Instead of using the foreach loop, use the native array_sum Methode.. This is what the code should look like:


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

echo $sum;


Okay awesome thank you both for the explanations!