tony9099
tony9099

Reputation: 4717

simple for loop not working in php

I know this may sound trivial. But why is the below code not entering in php?

for ($k = "$i"; $k < 0; $k--)
{
//random
}

where 'i' is a value from an upper for loop.

Upvotes: 0

Views: 489

Answers (4)

Matt Bryant
Matt Bryant

Reputation: 4961

You are subtracting each time, while checking that it is less than 0. This will cause an infinite loop, as it will never not be less than 0.

It seems unlikely that you want to do this. The code you probably wanted is:

for ($k = $i; $k >= 0; $k--) {
    //random
}

Upvotes: 0

Daryl Gill
Daryl Gill

Reputation: 5524

for ($k = "$i"; $k < 0; $k--)
{
//random
}

remove the quotes around $i and also give $i a value, so your code looks like the following:

$i = 0;
for ($k = $i; $k < 0; $k--)
{
//random
}

Upvotes: 0

seanmk
seanmk

Reputation: 1963

The main problem is that your conditional is backwards if you are using a decrementing counter. It should presumably be $k >= 0. It may also be a problem that you have quotes around $i, which are unnecessary and problematic.

Upvotes: 5

Kirk Backus
Kirk Backus

Reputation: 4866

Why not just this?

for ($k = $i; $k >= 0; $k--)
{
//random
}

EDIT

I just noticed, that your logic will create an infinite loop! I fixed the code...

Upvotes: 2

Related Questions