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

Php Why the numbers display 321?

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

?>

3 Answers

Konstantinos Pedarakis
Konstantinos Pedarakis
21,301 Points

no! the $output shows the value of the variable $number that you are looping each time and then you adding the previous value of the $output. when you loop for the 1st time the $output is " ". then you assign the $number plus $output to the $output. so its 1 + " "(nothing). so its 1. then for the second time the $number becomes 2. and you assing the $number plus the $output to $output again, but now is 2 plus 1 as strings. so the $output is 21.

oh ok thanks very much!

Konstantinos Pedarakis
Konstantinos Pedarakis
21,301 Points

your code seems strange. What are you trying to do? you actual code just adds the numbers inside your loop as strings. for example when the loop execeutes for the first time, the i = 1 so the condition is true and the output is 1. you store as a string in the variable $output. then for the second time the i=2 your output is 2 and you concatenate the output(which is 1), so now your aoutput is 2+1 but as strings this is 21 actually. then for the last time the i=3 your output is 3 and you concatenate the previous output which is (21). so 321. so the final output that you echo is not a number. is the string 321. i dont know what you are trying to acheive here. please let me know if you need any further explanations. Cheers.

Matthew Bilz
Matthew Bilz
15,829 Points

This is a code challenge on a PHP developing course, he just copied and pasted it for a demo. Otherwise, spot on!

Konstantinos Pedarakis
Konstantinos Pedarakis
21,301 Points

oh ok thanks Matthew Bilz . at least i believe i clarified things a lil bit better. :)

To clarify the $output variable is showing the value of $i ? That is it?