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

Cannot make sense of the quiz involving foreach

I am trying to understand the following code in quiz but to no veil.

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

1 Answer

Lindsey Somerset
Lindsey Somerset
10,592 Points
<?php
$output = $number . $output;

Adding a string type to a number type converts that number to a string. So instead of addition, concatenation of the two strings happens.

When $number is 1 --- $output = 1 + "" == "1" + "" results in "1"

When $number is 2 --- $output = 2 + "1" == "2" + "1" results in "21"

When $number is 3 --- $output = 3 + "21" == "3" + "21" results in "321"

4 won't be included because when $i = 4 it is not less than 4. A few other languages do this as well (JavaScript and Java, at least I think). Please let me know if this helped!