1

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.

2
  • If I understand your logic, shouldn't you be using for ($counter=0; $counter < 2; $counter++) since, you're setting x to be 0, you're going to get 12 and 24 returned Commented Feb 12, 2014 at 23:22
  • 1
    You are reseting $x to another value in your for loop. Try to AVOID using globals though: they're difficult to debug, hinder testing, and are generally frowned upon. Commented Feb 12, 2014 at 23:22

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I cant believe I didn't notice that! thanks a lot for everyone's responses.
1

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.