Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Nested for loop - pyramid shape

Tags:

php

for-loop

Using a nested for loop in PHP, i have to create the following pattern:

- - - - - - - - - - - - - - -
- - - - - - - + - - - - - - -
- - - - - - + + + - - - - - -
- - - - - + + + + + - - - - -
- - - - + + + + + + + - - - -
- - - + + + + + + + + + - - -
- - + + + + + + + + + + + - -
- + + + + + + + + + + + + + -
+ + + + + + + + + + + + + + +

I have tried to do this and wrote the following code:

$pluscount = -1;
$mincount  = 8;
for ($rows = 0; $rows <= 8; $rows++) {
    for ($min = 0; $min < $mincount; $min++) {
        echo " - ";
    }
    for ($plus = 0; $plus < $pluscount; $plus++) {
        echo " + ";
    }
    for ($min = 0; $min < $mincount; $min++) {
        echo " - ";
    }
    $pluscount += 2;
    $mincount  = (15 - $pluscount) / 2;
    echo "<br />";
}

However, this results in:

- - - - - - - - - - - - - - - - 
- - - - - - - + - - - - - - - 
- - - - - - + + + - - - - - - 
- - - - - + + + + + - - - - - 
- - - - + + + + + + + - - - - 
- - - + + + + + + + + + - - - 
- - + + + + + + + + + + + - - 
- + + + + + + + + + + + + + - 
+ + + + + + + + + + + + + + + 

As you can see, the first line is incorrect. How do I solve this?

like image 540
Daan Avatar asked Feb 06 '26 11:02

Daan


2 Answers

You can replace the sub loops with str_repeat(), and use the substr() to trim the last part.

for ( $row = 8; $row >= 0; $row-- ) {
    echo substr( 
       str_repeat( " - ", $row ) . str_repeat( " + ", max( 15 - ($row*2), 0 ) ) . str_repeat( " - ", $row ), 
    0, 45 );
}
like image 92
Danijel Avatar answered Feb 09 '26 03:02

Danijel


$pluscount = -1;
$mincount  = 8;
for ($rows = 0; $rows <= 8; $rows++) {
    for ($min = 0; $min < $mincount; $min++) {
        echo " - ";
    }
    for ($plus = 0; $plus < $pluscount; $plus++) {
        echo " + ";
    }
    for ($min = 0; $min < min($mincount, 7); $min++) {
        echo " - ";
    }
    $pluscount += 2;
    $mincount  = (15 - $pluscount) / 2;
    echo "<br />";
}
like image 21
Halayem Anis Avatar answered Feb 09 '26 01:02

Halayem Anis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!