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 trialFelipe Marconatto Ochman
4,494 PointsPhp 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
21,301 Pointsno! 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.
Konstantinos Pedarakis
21,301 Pointsyour 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
15,829 PointsThis is a code challenge on a PHP developing course, he just copied and pasted it for a demo. Otherwise, spot on!
Konstantinos Pedarakis
21,301 Pointsoh ok thanks Matthew Bilz . at least i believe i clarified things a lil bit better. :)
Felipe Marconatto Ochman
4,494 PointsTo clarify the $output variable is showing the value of $i ? That is it?
Felipe Marconatto Ochman
4,494 PointsFelipe Marconatto Ochman
4,494 Pointsoh ok thanks very much!