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,686 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,686 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.