Himanshu Upadhyay
Himanshu Upadhyay

Reputation: 743

Pyramid pattern in php

I have pattern like this.

    * 
    * * 
    * * * 
    * * * * 
    * * * * * 

my code is as follows

for($i=1;$i<=5;$i++){
    for($j=1;$j<=5;$j++){
        echo "  ";
    }
    for($m=1;$m<=$i;$m++){
        echo "*  ";
    }
    echo "</br>";
}

but I want pattern like the following one. I have tried but could not get it.

* 
* * *
* * * * *
* * * * * * * 
* * * * * * * * *

Upvotes: 0

Views: 308

Answers (3)

Akis
Akis

Reputation: 178

Alternatively from Uchida i notice that you want to have 5 rows where first row has the 1st odd number of * (1 is the first odd number) and the last row has the 5th odd number of * (9 nine is the 5th odd number).

You can achieve that by applying that logic into code:

 for($i=0;$i<=4;$i++) {   // Here we define the amount of rows notice we start from '0'
    for($m=1;$m<=(2*$i+1);$m++) { // Here we compute the right odd number
       echo "*  ";
    }
    echo "</br>";       
 } 

Upvotes: 0

sandeep soni
sandeep soni

Reputation: 303

Try below code. working fine

<?php
for($i=1;$i<=10;$i+=2){
for($j=1;$j<=$i;$j++){
echo "*&nbsp;";
}
echo "<br>";
}
?>

Upvotes: 0

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21422

Try this simply using str_repeat and $i += 2 instead of $i++

for($i = 1;$i < 10; $i+=2){
    echo str_repeat('* ',$i)."<br>";
}

Fiddle

Upvotes: 4

Related Questions