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

Kireeti K
Kireeti K
9,675 Points

what is the output of this program?

<?php

$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;

?>

I assume the output is 1234 and my explanation is as follows

$output is null while declaring it and hence

$output = 1.NULL; 1st iteration $output is now 1 $output = 1.2; 2nd iteration $output is now 12 $output = 12.3; 3rd iteration $output is now 123 $output = 123.4; last iteration $output is now 1234

If condition Fails..

While answering the quiz i got bummer for 1234, Please correct me where did i go wrong and what is the output

Thanks!

4 Answers

Kireeti K
Kireeti K
9,675 Points

Finally Understood..

i is set to 1 so it only loops 3 times and i concatenated the wrong way.. The answer is 321

Simon Coates
Simon Coates
28,692 Points

A couple people have been thrown by that one. you get so used to thinking $variableName = variableName... or the compound operator syntax (+= etc), that you seen what you expect to see.

Kireeti K
Kireeti K
9,675 Points

Hello Simon, Thanks for the reply. Sorry but i dont understand can you please elaborate..

Simon Coates
Simon Coates
28,692 Points

With code, there's a tendency to see what you think it should mean. so people look at $output = $number . $output; and think $output = $output. $number; People expect to see 1234, more than 321.