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

Cannot 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
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!