PHP Build a Basic PHP Website (2018) Listing and Sorting Inventory Items Working with Functions

György Varga
György Varga
19,198 Points

Quiz question

Hi!

Can you help me understand why this code outputs '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;

?>

Thank you!

1 Answer

You are offsetting your $i at the start of the loop, so you are missing the first index of the array

 $i = $i + 1;

What happens here is that the first time the loop runs, it is making $i set to 1 instead of zero. Since the length of the array is 4, when the loop goes through the last index, it sees that $i = 4, so your if condition is now false. If you move that after your if block, it should now be 4321.

$numbers = array(1,2,3,4);

$total = count($numbers);

$sum = 0;

$output = "";

$i = 0;

foreach($numbers as $number) {



    if ($i < $total) {

        $output = $number . $output;

    }

  $i = $i + 1;

}

echo $output;

Is your intention to make the numbers go in order?

$output = $number . $output;

The above code there is appending the $number to the beginning of $output. Reversing those two will make the numbers go in traditional order. Another suggestion is that depending on what it is you are trying to do, you can just echo out $number inside of your if block instead of concating the string and doing it at the end of the loop. Like this:

foreach($numbers as $number) {

    if ($i < $total) {

        echo $number;

    }

  $i = $i + 1;

}

Finally you can take $i = $i + 1; and turn it into `$i++', which does the same thing. Let me know if this helps or you still find yourself confused.

György Varga
György Varga
19,198 Points

Thank you! :) I cannot understand why the numbers are in reverse order?