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 trialammarkhan
Front End Web Development Techdegree Student 21,661 PointsCannot make sense of the quiz involving foreach
I am trying to understand the following code in quiz but to no veil.
$numbers = array(1,2,3,4);
$total = count($numbers);
$sum = 0;
$output = "";
$i = 0;
foreach($numbers as $number) {
$i = $i + 1;
if ($i < $total) {
$output = $number . $output;
}
}
echo $output;
1 Answer
Lindsey Somerset
10,592 Points<?php
$output = $number . $output;
Adding a string type to a number type converts that number to a string. So instead of addition, concatenation of the two strings happens.
When $number is 1 --- $output = 1 + "" == "1" + "" results in "1"
When $number is 2 --- $output = 2 + "1" == "2" + "1" results in "21"
When $number is 3 --- $output = 3 + "21" == "3" + "21" results in "321"
4 won't be included because when $i = 4 it is not less than 4. A few other languages do this as well (JavaScript and Java, at least I think). Please let me know if this helped!