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

Mirko Nobelen
Mirko Nobelen
7,507 Points

I really don't get how this is 6 (i ran it trough workspace) but don't understand how it got to this.

Sorry I am not getting this.

The answer is 6 (i ran it trough workspace) but don't understand how it got to this.

Julian Gutierrez
Julian Gutierrez
19,201 Points

Try going step by step, just a hint the answer is not 6.

Mirko Nobelen
Mirko Nobelen
7,507 Points

Thank you for your reply

2 Answers

Are you referring to this function?

<?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) {

        $sum = $sum + $number;

    }

}

echo $sum;

?>
Mirko Nobelen
Mirko Nobelen
7,507 Points

Many thanks for helping out a newbie, I get it now!

If you were referring to the function I posted above this should help you have a better understanding of what is happening:

<?php

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

$total = count($numbers);
echo 'total = '. $total .'<br />';

$sum = 0;
echo 'sum = '. $sum .'<br />';

$output = "";

$i = 0;

foreach($numbers as $number) {

    $i = $i + 1;


    echo '$i = '. $i .'<br />';


    if ($i < $total) {

    echo 'When our condition is met $sum = '. $sum .' and $number = '. $number .'<br />';
        $sum = $sum + $number;

    }

}

echo $sum;

?>