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 trialsamanthametcalfe2
5,820 PointsBuild 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
andren
28,558 PointsThat 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.