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.
for ($counter=0; $counter < 2; $counter++)since, you're setting x to be 0, you're going to get 12 and 24 returned$xto another value in yourforloop. Try to AVOID using globals though: they're difficult to debug, hinder testing, and are generally frowned upon.