Shibbir
Shibbir

Reputation: 257

Php for loop issue

Hi I'm Learning php and trying to do a for loop look like this wtih this code:

for($x=1; $x<=20; $x++){
    echo $x;
    $x = $x + 3; //5    
    echo "<br/>";
}

It's produce

 1
 5
 9
 13
 14

But I want it should be...

1 
5
10
15
20

Upvotes: 0

Views: 140

Answers (4)

Gaurav Kachhadiya
Gaurav Kachhadiya

Reputation: 17

Try this:

for($x=1; $x<=20; $x++) {
    if($x%5==0 || $x==1) {
        echo $x;
        echo "<br>";
    }
}

Upvotes: 0

Dwza
Dwza

Reputation: 6565

there are more than one solution.

one is:

for($x=1; $x<=20; $x++){
    if(!($x % 5) || $x==1)
        echo $x . "<br />";    
}

Explination

% is the modulo operator. It returns the devision rest.

lets say $x is 3 than 3 % 5 would return 3 because the result 3/5 = 0 rest 3

if its $x is 10, it return 0. 10/5 = 2 rest 0

In the if-statement I use !-not operator. This turns around the result.

Because if takes 1+ (one and more) as true and 0- (zero and less) as false

So rest of 3 would be positiv (true) but in this case i want it to be false. So I turn arount the true/false with !

% - Modulo

R - Rest

1 % 5 = 0 R 1  // would say true to if
2 % 5 = 0 R 2  // would say true to if
3 % 5 = 0 R 3  // would say true to if
4 % 5 = 0 R 4  // would say true to if
5 % 5 = 1 R 0  // would say false to if
6 % 5 = 1 R 1  // would say true to if

and so on...

Upvotes: 1

munsifali
munsifali

Reputation: 1732

try this.

    $x = 1;

for ($j = 1; $j <= 20; $j++) {

echo $x, "<br/>";
if ($x == 1) {
    $x = $x + 4;
} else {

    $x = $x + 5;
   if($x > 20){break;}
}
}

if this answer is work for you please mark the answer.

Upvotes: 0

Daniel W.
Daniel W.

Reputation: 32260

for ($x = 0; $x <= 20; $x += 5) {
    echo ($x == 0 ? 1 : $x), '<br>';
}

Or:

foreach (range(0, 20, 5) as $x) {
    echo ($x == 0 ? 1 : $x), '<br>';
}

You can't produce the sequence without 1 extra condition because the delta differs in the first step:

 1  + 4 ...
 5  + 5
10  + 5
15  + 5
20  + 5

Upvotes: 3

Related Questions