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