Page 1 of 1

default value of variables

Posted: Sat May 03, 2003 4:11 am
by moogue
hello,

look at this (example-)code:

Code: Select all

for ($i=0; $i<5;$i++) 
   &#123;
   $a += $i;
   &#125;
this repeatly adds the value of $i to variable $a.
my question is:
If $a was never used before in this script, can I be sure that it always has "0" as its default integer value and $a is ALWAYS 10 after running this loop or could it be possible that it has another value. I couldn't find any informaton about this. I know in C a Varible should be initialized (with 0 f.ex.). I made some tests and the vars never had another value than zero - was this fortunity or can I be really sure that it neve rhappens?

Posted: Sat May 03, 2003 4:51 am
by volka
it should be initialized in php, too.
Otherwise you'll get a warning because there is no variable $a to be incremented in the first loop iteration.

Code: Select all

<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
for ($i=0; $i<5;$i++)
{
	$a += $i;
}
?>
vs.

Code: Select all

<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
$a = 0;
for ($i=0; $i<5;$i++)
{
	$a += $i;
}
?>

Posted: Sat May 03, 2003 5:29 am
by moogue
thanks a lot