0

The challenge is to write a for loop to print square numbers to the browser that are not divisible by 3. I am not getting the expected output which is 1,4,16,25,49,64,100



<html lang="en">
    <head>
        <title>Square Numbers</title>
    </head>
    <body>
        <?php
            for ($a=1;$a<=10;$a++){
                if ($a % 3 != 0){
                    echo $a * $a . ",";
                }
            }
        ?>


    </body>
</html>

3 Answers3

1

Probably the cleanest way is to push the results to an array and then implode it using , as the glue on output:

$result = [];

for ($a=1;$a<=10;$a++){
    if ($a % 3 != 0){
        $result[] = $a * $a;
    }
}

echo implode(",", $result); // 1,4,16,25,49,64,100

Implode joins array elements with the specified string (referred to as the "glue"):

implode ( string $glue , array $pieces ) : string

You can see it in action here

Brett Gregson
  • 5,867
  • 3
  • 42
  • 60
1

One of the common technique is to add them to an array, then use implode to attach them with glue string ("," for your case). That way there is no need of knowledge when the array is going to end.

<html lang="en">
    <head>
        <title>Square Numbers</title>
    </head>
    <body>
        <?php
            $values = array();
            for ($a=1;$a<=10;$a++){
                if ($a % 3 != 0){
                    $values[] = $a * $a;
                }
            }
            echo implode(',', $values);
        ?>


    </body>
</html>
Koala Yeung
  • 7,475
  • 3
  • 30
  • 50
1

A solution without creating an extra array:

<html lang="en">
    <head>
        <title>Square Numbers</title>
    </head>
    <body>
        <?php
            for ($a=1;$a<=10;$a++){
                if ($a % 3 != 0){
                    echo ($a * $a) . ($a < 10 ? "," : "");
                }
            }
        ?>
    </body>
</html>
Claudio
  • 5,078
  • 1
  • 22
  • 33