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?
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 );
}
$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 />";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With