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 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,109 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!