Community: I am studying PHP from scratch and wanted to understand the following:
<?php
$a = 1;
while($a < 1000){
$b = 0;
$b = $a + $b;
echo "$b <br>";
$a = $a + 3;
}
?>
I assume that as long as variable $a is less than 1000 it prints 3 numbers from 1 to 1000. The question is: Why should I initialize variable $b to 0 and then add it to variable $a? I saw this in a basic exercise.
In truth, the variable $b is not doing anything important, it is not an accumulator because it is cleaned again when repeating the cycle, therefore, it is repeating the value of $a.
If you remove the variable $b as shown in the code below the result will be the same.
Without the Variable $b
Result Executing your code (includes variable $b)
I recommend the following
Since as you had "b" it always went to 0 every time it saw the cycle, so it was going to add only a+3, also if you are going to do operations as a good practice it is always better to initialize the variables, although it does not have the exercise makes a lot of sense, I consider that this is the best practice
UPDATE
If you don't initialize b you will get the following
So I would recommend that if you do
Any questions I'll gladly help you