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

5,820 Points

Build a Basic PHP Website Quiz $output

$numbers = array(1,2,3,4); $total = count($numbers); $sum = 0; $output = ""; $loop = 0;

foreach($numbers as $number) { $loop = $loop + 1; if ($loop < $total) { $output = $number . $output; } }

echo $output;

Why is 321 the answer?

1 Answer

28,521 Points

That code was written to be intentionally confusing, but if you break the loop down iteration by iteration you can start to see what is happening. The main thing to keep in mind is that $output is a string, not a number. And within the loop string concatenation is used to add to it.

So when this line runs:

$output = $number . $output; 

Whatever number is stored in $number is added to the beginning of the $output string. For example in the first iteration of the loop $output starts out with "" and then has 1 added at the beginning which results in "1". Then during the next iteration it starts out with "1" and then has 2 added at the start of the string, which results in "21". And the same thing happens during the third iteration.

That's the key here, we are not adding numbers together mathematically, but modifying a string by setting it equal to itself with a number added to its start. The reason why you get "321" and not "4321" is that the string concatenation only happens if the if statement runs. And it only runs if $loop is less than $count. $count hold the length of the array (4) and $loop is increased by 1 each loop. During the final loop $loop is set equal to 4, since 4 is not less than 4 the if statement does not run. Which is why 4 is not added to the $output string.