1

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?

4
  • 2
    In your first iteration you say: 0 > 8 -> IF TRUE enter the loop ELSE don't run the loop Commented Jul 28, 2015 at 15:16
  • Yes, maybe you meant $i < 8? Commented Jul 28, 2015 at 15:22
  • $i is never higher than 8 in your case, hence the if is getting "skipped". So yes, the problem is in the first loop, and it actually is that the condition you wanted is probably $i < 8 instead. Commented Jul 28, 2015 at 15:24
  • Oh yeah! the loop is not being called at all! Thanks Guys! :D Commented Jul 28, 2015 at 15:26

3 Answers 3

1

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.

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

Comments

0

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.

Comments

0

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.

1 Comment

Thanks so much for this one, helped a lot :)

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.