Reputation: 9
I am just learning about php and i cant understand why i get different results from the two following code snippets.
Snippet 1:
<?php
$x = 22;
$y = 12;
$counter = 0;
function add()
{
if ($GLOBALS['counter'] == 0)
{
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
else
{
$GLOBALS['z'] += $GLOBALS['y'];
}
$GLOBALS['counter'] ++;
}
add();
echo "$z <br>";
add();
echo "$z <br>";
?>
the first returns 34 , 46 as expected.
Snippet 2:
<?php
$x = 22;
$y = 12;
$counter = 0;
function add()
{
if ($GLOBALS['counter'] == 0)
{
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
else
{
$GLOBALS['z'] += $GLOBALS['y'];
}
$GLOBALS['counter'] ++;
}
for ($x=0; $x < 2; $x++)
{
add();
echo "$z <br>";
}
?>
The second returns 12 , 24.
This may sound very simple but i can honestly not work out why this isn't working.
Any help is appreciated.
Upvotes: 1
Views: 46
Reputation: 46375
When you create a loop
for ($x=0; $x < 2; $x++)
{
add();
echo "$z <br>";
}
You overwrite the definition of x
from earlier... Change it to
for ($q=0; $q < 2; $q++)
{
add();
echo "$z <br>";
}
and you'll see...
Upvotes: 1
Reputation: 141827
You are reusing the variable name $x
for your loop counter. You're setting $x
to 0
, so you get 0 + 12
when you do $_GLOBALS['x'] + $_GLOBALS['y']
. You must rename it to something you're not already using. I recommend changing it to $i
:
for ($i = 0; $i < 2; $i++)
{
add();
echo "$z <br>";
}
I also recommend that you avoid using $_GLOBALS
in general.
Upvotes: 2