tanhernandez
tanhernandez

Reputation: 98

PHP Variable Scope Weird Trouble

I was coding PHP when suddenly Im being confused with variable scopes.

If I do the loop like this ...

function foo()
{

    $ctr = 0;

    for ($i = 0 ; $i > 8 ; $i++)
    {

        $ctr = $ctr + 1;

    }

    return $ctr;

}

$ctr returns a 0.

But if I do the loop like this ...

function foo()
{
    $collections = //This has 7 counts;        

    $ctr = 0;

    foreach ($collections as $collection)
    {
         $ctr = $ctr + 1;
    }

    return $ctr;

}

CTR IS RETURNING 7!

So what's is the problem in the first loop?

Upvotes: 1

Views: 47

Answers (3)

ThomasVdBerge
ThomasVdBerge

Reputation: 8140

The for loop you are trying to do seems to be a bit wrong.

    for ($i = 0 ; $i > 8 ; $i++)
                  ^^^^^^

Means, Set $i to 0. For as long as $i is bigger than 8, do this loop then increment.

Since $i is set to 0, the condition is never met, so the loop is never executed.

Change $i > 8 to $i < 8.

Upvotes: 1

Wahib Mkadmi
Wahib Mkadmi

Reputation: 646

The problem in the first loop might be hard to spot, I must say.

It's about the $i > 8, your code doesn't even enter the loop. Invert the operator, ($i = 0 ; $i < 8 ; $i++)

This worked for me.

Upvotes: 0

Marc B
Marc B

Reputation: 360732

Your loop condition:

for ($i = 0 ; $i > 8 ; $i++)
              ^^^^^^

since the loop starts at 0, you have 0 > 8, which is false, and your loop terminates immediately. Remember, loops terminate when that 2nd argument becomes false. it has to be TRUE for the loop body to execute.

Upvotes: 0

Related Questions