0

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

4 Answers 4

3
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
Sign up to request clarification or add additional context in comments.

2 Comments

I think the second way is good but it's more slowly than the first way.
@LionKing It's only a theoretical performance difference, not noticable in such a small use case.
1

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

3 Comments

DanFromGermany has a more efficient answer below. This one loops 20 times when you only need 5 loopings.
@Shibbir: I don't know how did you accept this answer and you don't understand it
@LionKing because it works and its tiny. I bet there are many thing in life you do, even if you don't know what really happens. May you drive a care whithout knowing what material the gas made out...
0

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.

1 Comment

I want to stop it to 20.
0

Try this:

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

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.