the code keep printing same word two times

Viewed 143

That's what I am trying to do:

  • Output the numbers from 1 to 100

• Where the number is divisible by three (3) output the word “foo”

• Where the number is divisible by five (5) output the word “bar”

• Where the number is divisible by three (3) and (5) output the word “foobar”

I was able to do that, but it is printing two times foobar as shown in the output below rather just once. What am I doing wrong?

Here is my currenct code:

<?php

for ($i = 1; $i<=100; $i++) {
    if ($i % 3 && $i % 5) {
        echo $i;
    } else {
        if ($i % 3 == 0) {
            echo "foo";
        }
        if ($i % 5 == 0) {
            echo "bar";
        }
        if ($i % 3 == 0 && $i % 5 == 0) {
            echo "foobar\r\n";
        }
    }
    //line breaks to enhance output readability
    echo "\r\n";
}

?>

Current Output:

1
2
foo
4
bar
foo
7
8
foo
bar
11
foo
13
14
foobarfoobar

16
17
foo
19
bar
foo
22
23
foo
bar
26
foo
28
29
foobarfoobar

31
32
foo
34
bar
foo
37
38
foo
bar
41
foo
43
44
foobarfoobar

46
47
foo
49
bar
foo
52
53
foo
bar
56
foo
58
59
foobarfoobar

61
62
foo
64
bar
foo
67
68
foo
bar
71
foo
73
74
foobarfoobar

76
77
foo
79
bar
foo
82
83
foo
bar
86
foo
88
89
foobarfoobar

91
92
foo
94
bar
foo
97
98
foo
bar

As posted in answer I tried doing :

  if ($i % 3 && $i % 5) {
        echo $i;
    } else {
        else if ($i % 3 == 0) {
            echo "foo";
        }
        else if ($i % 5 == 0) {
            echo "bar";
        }
       else  if ($i % 3 == 0 && $i % 5 == 0) {
            echo "foobar\r\n";
        }
    }

Is this right? I am not able to post in comment properly all this code.

2 Answers

It is not printing "foobar" twice. It is printing "foo", then "bar", then "foobar", without any spaces. This happens because all three if conditions trigger. Use else or elseif to make sure that when one if triggers, no others are checked.

EDIT:

    // ...
    if ($i % 3 == 0 && $i % 5 == 0) {
        echo "foobar";
    } elseif ($i % 3 == 0) {
        echo "foo";
    } elseif ($i % 5 == 0) {
        echo "bar";
    }
    // ...

I guess this is what you are looking for

<?php
for ($i = 1; $i<=100; $i++) {

        if (($i % 3 == 0)){
            echo "foo";
            if (($i % 5 == 0)){
                echo "bar";
            }
            echo "</br>";
        }
        elseif (($i % 5 == 0)){
            echo "bar";
            echo "</br>";
        }
        else {
            echo $i;
            echo "</br>";
        }
}
?>

This will give you an output like below

1
2
foo
4
bar
foo
7
8
foo
bar
11
foo
13
14
foobar
16
17
foo
19
bar
foo
22
23
foo
bar
26
foo
28
29
foobar
31
32
foo
34
bar
foo
37
38
foo
bar
41
foo
43
44
foobar
46
47
foo
49
bar
foo
52
53
foo
bar
56
foo
58
59
foobar
61
62
foo
64
bar
foo
67
68
foo
bar
71
foo
73
74
foobar
76
77
foo
79
bar
foo
82
83
foo
bar
86
foo
88
89
foobar
91
92
foo
94
bar
foo
97
98
foo
bar
Related