Rimpy Kakeyalia
Rimpy Kakeyalia

Reputation: 47

Printing a number triangle pattern with PHP

I want to print this pattern with PHP using for loops:

10 9 8 7 6
10 9 8 7
10 9 8
10 9
10

Right now, I'm using this:

for ($i=10; $i>5; $i--)
{   
   for ($j=$i; $j>5; $j--)
    {   
       echo $j.' ';

    }

    echo "</br>";    
} 

and it is printing this :

10 9 8 7 6 
9 8 7 6 
8 7 6 
7 6 
6 

Upvotes: 1

Views: 2968

Answers (5)

Shanu k k
Shanu k k

Reputation: 1285

Try this

<?php

    for ($i=5; $i>0; $i--) {   
        for ($j=10; $j>10-$i; $j--) {   

            echo $j.'&nbsp;';

        }
        echo "<br/>";    
    }


    ?>

Output will be

10 9 8 7 6 
10 9 8 7 
10 9 8 
10 9 
10

Upvotes: 0

Akshay Hegde
Akshay Hegde

Reputation: 16997

$ cat test.php
<?php

/* Start and End */
$start = 10;
$end   = 5;

/* Field Sep */
$field_sep = "&nbsp;";

/* Row Sep */
$row_sep   = "<br/>\n";

/* Rows */
for($j=1; $j<=5; $j++)
{
    /* Columns */   
    for($i=$start; $i>=$end+$j; $i--){
        echo ($i==$start?$i:$field_sep.$i);
    }
        echo $row_sep;
}
?>

Output

$ php test.php
10&nbsp;9&nbsp;8&nbsp;7&nbsp;6<br/>
10&nbsp;9&nbsp;8&nbsp;7<br/>
10&nbsp;9&nbsp;8<br/>
10&nbsp;9<br/>
10<br/>

With

/* Field Sep */
$field_sep = " ";

/* Row Sep */
$row_sep   = "\n";

Output

$ php test.php
10 9 8 7 6
10 9 8 7
10 9 8
10 9
10

Flowchart

Flowchart

Upvotes: 0

Oscar Zarrus
Oscar Zarrus

Reputation: 790

SOLUTION 1: collect numbers to an array and echo it at the end

$results = array(); // set an empty array;
$from = 10; // set from 
$to = 6; // set to
$spaceChr = '&nbsp;'; // set space char 
$LFChr = "<br />"; // set Line Feed char
foreach(range($from,$to) as $k=>$c){ 
    foreach(range($from,$to+$k) as $v){
        $results[$k][] =$v;
    }
    $results[$k] = implode($spaceChr, $results[$k]); 
}
$results = implode($LFChr, $results);
echo $results;

OR SOLUTION 2: echo each number during loop:

$from = 10;
$to = 6;

foreach(range($from,$to) as $k=>$c){
    foreach(range($from,$to+$k) as $v){
        echo $v . '&nbsp;';
    }

    echo "<br />";
}

Upvotes: 0

arkascha
arkascha

Reputation: 42959

This would be an immediate fix for your code for easy CLI usage:

<?php
define('STOP_NUMBER', 10);
define('START_NUMBER', 5);

for($i=START_NUMBER; $i<=STOP_NUMBER; $i++) {
  for($j=STOP_NUMBER; $j>=$i; $j--) {
    echo $j . ' ';
  }
  echo "\n";
}

Here the same with HTML markup in the output:

<?php
define('STOP_NUMBER', 10);
define('START_NUMBER', 5);

for($i=START_NUMBER; $i<=STOP_NUMBER; $i++) {
  for($j=STOP_NUMBER; $j>=$i; $j--) {
    echo $j . '&nbsp';
  }
  echo "<br />\n";
}

Upvotes: 1

Haotian Liu
Haotian Liu

Reputation: 886

for ($i=5; $i>0; $i--) {   
    for ($j=10; $j>10-$i; $j--) {   
        echo "{$j} ";

    }
    echo "<br/>";    
}

Upvotes: 3

Related Questions