default value of variables

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
moogue
Forum Newbie
Posts: 3
Joined: Sat May 03, 2003 4:11 am
Location: Germany

default value of variables

Post 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?
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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;
}
?>
moogue
Forum Newbie
Posts: 3
Joined: Sat May 03, 2003 4:11 am
Location: Germany

Post by moogue »

thanks a lot
Post Reply