Reputation: 275
I am trying to print a star pattern using php. I am trying to print this:
*
**
***
****
*****
my code:
for($i=1; $i<=5; $i++){
for($j=1; $j<=5; $j++){
if($j>= (6-$i)){
echo "*";
} else {
echo " ";
}
}
echo "<br>";
}
by doing this I should get above pattern but instead, I am getting this:
*
**
***
****
*****
Anybody can tell me why this is happening? Thanks in advance.
Upvotes: 0
Views: 127
Reputation: 48021
Honestly, I'd be using str_pad()
. However if you need to use loops for your class assignment, then decrementing $j
seems easier.
Demo: https://3v4l.org/9aY3S
for($i=1; $i<=5; ++$i){
for($j=5; $j>0; --$j){
echo $i < $j ? " " : "*";
}
echo "\n";
}
When rendering as html, you will need to use
to show consecutive spaces and <br>
for line breaks. Or if your font is one that gives a different character width for spaces and asterisks, then you can sync the width by changing fonts or use <span style="visibility:hidden">*</span>
for your non-asterisks.
Take your snippet to phptester.net to see how it is rendered as html.
Upvotes: 0
Reputation: 24393
Extra whitespace characters in HTML documents have no effect on the rendered output. If you look at the output page source, you will see that you are getting the correct result. Here are your options:
1) Send a Content-Type: text/plain
header:
header('Content-Type: text/plain');
Make sure to change your <br>
tags to newline characters ("\n"
, "\r\n"
, or PHP_EOL
)
2) Wrap what you have there with a <pre>
tag
echo '<pre>';
for($i=1; $i<=5; $i++){
for($j=1; $j<=5; $j++){
if($j>= (6-$i)){
echo "*";
} else {
echo " ";
}
}
echo "<br>";
}
echo '</pre>';
3) Use non-breaking spaces:
for($i=1; $i<=5; $i++){
for($j=1; $j<=5; $j++){
if($j>= (6-$i)){
echo "*";
} else {
echo " ";
}
}
echo "<br>";
}
On another note, here's a one-liner that will do the same thing as what you're trying to do without the additional for
loop and if/else
statements:
for ($i=1; $i<=5; $i++) {
echo str_pad(str_repeat('*', $i), 5, ' ', STR_PAD_LEFT) . PHP_EOL;
}
Upvotes: 1