I Didn't succeed to decipher the logic of this code

Hello, I am very new to programming and PHP. Here is a PHP code I admit I didn’t manage to decipher… I mean, I couldn’t understand why this code brings it’s final result?

I do understand there are 6 variables in this code and an internal foreach loop that runs through the array and includes an if-then statement, but I didn’t understand the logic of the code in general.

Can someone wrote a pseudocode for this in a stepped way and detail as much as possible in a didactic way for newcomers like me? I know this code is not minimalistic and might seem unusual - I found it in a practice sheet.

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

?>

Does this help:

<?php 

// best to show errors
    error_reporting(-1); ini_set(display_errros, 'true'); 

// useful function to display any type of variable
function fred($val, $sTitle='No Title???') {
    $tmp = 'width:88%; margin:1em auto; background-color:#0ff; color:red; padding:1em;';

    echo '<pre style="' .$tmp .'">';
      echo $sTitle .' => ';
        print_r($val);
    echo '</pre>';
}

// set variables and use CamelCase
    $aNumbers = array(1,2,3,4);
    $iCount   = count($aNumbers);
    $iSum    = 0;

// DEBUG - use 1 or 0 for true or false
    if(1) {
        fred($aNumbers, '$aNumbers');
        fred($iCount, '$iCount');
        fred($iSum, '$iSum');
    }

// main routine
echo 'Loop start';
   $i = 0;
    foreach($aNumbers as $iNumber) {
        // increment $i range 0.. < $iCount
        $i++; // same as: $i = $i + 1;

        // validation
          if ($i < $iCount) {
              // echo $i .', ';
            $iSum += $iNumber; // same as: $iSum = $iSum + $iNumber;

          }else{
              echo '<h3>';
                  echo 'Validation failed because:  $i >= $iCount <br />'; 
                  echo '$i(' .$i .') >= $icount(' .$iCount .')';
              echo '</h3>';
          }
    }
echo 'Loop finish';

// display results
    fred($iSum, '$iSum');

Output

$aNumbers => Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
$iCount => 4 
$iSum    => 0
Loop start:
  Validation failed because:  $i >= $iCount 
  $i(4) >= $iCount(4)
Loop finished

$iSum => 6

@Benos, was that what you were looking for, or do you want a simple step-by-step explanation in plain English of what your code is doing?

Here it is with comments describing what each line does:-

$numbers = array(1,2,3,4); // This create the array of four numbers.

//  As an alternative, it could have been written like tihs:- $numbers = range(1, 4);

$total = count($numbers);   // The "count" function gets the number of entries in the array. So $total will equal 4 in this case.

$sum = 0;   // Creates the $sum variable, with a value of 0.

$output = "";   // Creates an empty string variable, which does not appear to be used anywhere.

$i = 0;     // Creates the $i variable, with a value of 0, to be used as a "counter" in the loop.

foreach($numbers as $number) {  // Begins the loop, to go through each entry in the array $numbers, and naming the value of each entry $number

    $i = $i + 1;    //  This increases the value of $i by an increment of 1 at the beginning of every pass of the loop.
    
    //  As an alternative, it could have been written like tihs:- $i++;

    if ($i < $total) {  // This condition checks if the value of $i is "less than" (<) the number of entries in the array ($total).

        $sum = $sum + $number;  // A simple mathematical operator. It adds to the value of $sum, the value of the current array value in the loop.

    }   // ends the if condition

}   // ends the foreach loop

echo $sum;  // Displays the value of $sum on the page.

Note that the script does not add the last array value (4) to the sum. Because on that pass of the loop, the value of $i becomes 4, meaning it not less than the number of entries in the array (it is equal) and the if condition is not met, and therefore skipped.
So the result is 6.
0 + 1 + 2 + 3 = 6

2 Likes

So much thanks for this graceful detailing! I think I missed only one thing: Why we did 1+2 (for $number)? Where this is been done? I though it would stay 0 in this case.

I’m not sure what you mean.
But this is what happens in the loop, as if it were verbose code showing values rather than variable names.

// first pass $number = 1
1 = 0 + 1; // sets the $i value
if (1 < 4) {  // true
   1 = 0 + 1 ; // sets the $sum value
}
// second pass $number = 2
2 = 1 + 1;
if (2 < 4) {  // true
   3 = 1 + 2 ;
}
// third pass $number = 3
3 = 2 + 1;
if (3 < 4) {  // true
   6 = 3 + 3 ;
}
// fourth pass $number = 4
4 = 3 + 1;
if (4 < 4) {}  // false!! Skip this part
// loop ends. $sum = 6
1 Like

I meant to ask, why is the answer 0+1+2+3 ?

The zero came from the $sum=0 right? and the 1+2+3 comes from the array digits?

I think I just missed one thing - Why are the 1,2,3 digits become 1+2+3 ? That’s all I missed I think.

The addition is done on this line

$sum = $sum + $number;

Look at the sequence above.
$sum starts as 0.
First 1 is added to $sum (1+0), so $sum is now 1.
Next 2 is added (1+2), $sum is now 3.
Then 3 is added (3+3), $sum is now 6.
4 does not get added.
The result is 6.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.