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 Working with Functions

the answer is 321 but have no idea how

Sorry I have no idea how it get's to this answer

1 Answer

Kevin Korte
Kevin Korte
28,148 Points

So $numbers is an array of 1,2,34.

$total is a number that is the size of the array, which is 4. There are 4 numbers in the $numbers array.

$sum is zero, easy.

$output is just an empty initialized variable we are going to store our answer in

$i is our "iterator", we will use to keep track of our position in the loop.

Okay, the foreach loop. It's going to take each number in our array, and run the loop through it. Whatever number it's working on, will be stored in the temp variable $number. It's very common to see this design patter. Your array variable is plural, $numbers, because it's an array of values, but inside we are working on only one value of the array, so we use the singular version of the word, or $number.

So, the first line of code says: Foreach value in our number array, store it as a number. Sound round one.

Foreach(1,2,3,4 as 1) {

$i = 0 + 1;

if $i is less than $total (which is 4, remember) this will evaluate to true, so run the if statement.

$output = 1 concatenated to $output which is empty at this point.

and run the next foreach loop

Foreach(1,2,3,4 as 2) {

$i = 1+1;

if $i is less than $total (which is 4, remember) this will evaluate to true, so run the if statement.

$output = 2 concatenated to $output, which has the value of 1 right now. It's added to the front, so $output now equals 21

and again

Foreach(1,2,3,4 as 3) {

$i = 2+1;

if $i is less than $total (which is 4, remember) this will evaluate to true, so run the if statement.

$output = 3 concatenated to $output (remember, it's now 21). Now $output is 321

and again

Foreach(1,2,3,4 as 4)

$1 = 3+1;

if $i is less than $total (which is 4, remember) this will evaluate to true. BUT WAIT. $i = 4, and $total = 4. So $i is not less than $total, it's equal to total. So we DO NOT RUN this if statement. Skip it and move on.

Well that's the end of our foreach loop, we've ran through the entire array of numbers, so all that's left to do is echo $output, which is ..... 321

Many thanks for your wonderful support and very clear explanation, I finally get it!