Ram
Ram

Reputation: 21

Write a PHP code to print following number pattern

Write a PHP code to print following number pattern:
147
258
369

I am trying like this but its shows me shows below. how to convert column to row pattern.

<?php
    $num = "";
    for($i=1;$i<=9;$i++) {

        $num .= $i; 
        if($i%3==0){
            $num .="<br />";
        } 

    }
    echo $num;
?>
please help me

Upvotes: 2

Views: 795

Answers (2)

Talk2Nit
Talk2Nit

Reputation: 1135

Here is another way to get this output.

for($i = 1; $i <= 3; $i++) {
   $print = $i;
   for($j = 1; $j <= 3; $j++) {                
       echo $print;
       $print = $print + 3;
   }
   echo "<br />";
}    

Upvotes: 1

ascsoftw
ascsoftw

Reputation: 3476

You need to use for loop inside for loop to achieve this. Below is the code

$num = "";
for( $i = 1; $i <= 3; $i++ ) {
    for( $j = 0; $j <= 2; $j++) {
        $k = $i + ( $j * 3 );
        $num .= $k; 
    }
    $num .= "<br />"; 
}
echo $num;

Upvotes: 2

Related Questions