在php中使用if / for / do-while块中的变量[关闭]

If I am not wrong I used to use a new PHP variable in an if statement or a conditional loop block for the first time. What I want to say is like the following.

<?php

    for($i=0;$i<10; $i++)
    {
        $total += $i;
        $concat .= $i;
    }
 ?>

But today, when I look at the error logs, it says $total and $concat are undefined variables. Then I write this

    $total = 0;
    $concat="";   
    for($i=0;$i<10; $i++)
    {
        $total += $i;
        $concat .= $i;
    }
 ?>

It works with no error. Why? Asking just for curiosity.

It is because:

$total += $i;
$concat .= $i;

actually means:

$total  = $total+$i;
$concat = $concat.$i;

The first time you execute the loop, $total and $concat are undefined. So you get the error.

More details:

During the first run of the loop, you are writing

$total = the value of undefined $total + $i;

now, total is defined. Same for $concat.

Variables need to be declared before they are used. Depending on your error reporting you will not see the error.