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 trial

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.

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?