T. Raut T. Raut - 15 days ago 9
PHP Question

I Want to print Star pattern

I want to print star pattern like :

enter image description here
below is my code. but it doesn't work for me. How can i fix this problem.


for($i=1; $i<=5; $i++){
for($j=5; $j>$i; $j--){
echo " ";
}
echo "*";
for($j=1; $j<($i-1)*2; $j++){
echo " ";
}
if($i==1)echo "<br>";
else echo "*<br>";
}

for($i=4; $i>=1; $i--){
for($j=5; $j>$i; $j--){
echo " ";
}
echo "*";
for($j=1; $j<($i-1)*2; $j++){
echo " ";
}
if($i==1)echo "<br>";
else echo "*<br>";
}

?>

Answer

You should put all text that should keep form and not whitespace trimmed in between a <pre/> tag

<pre><?php
for($i=1; $i<=5; $i++){
    for($j=5; $j>$i; $j--){
        echo " ";
    }
    echo "*";
    for($j=1; $j<($i-1)*2; $j++){
        echo " ";
    }
    if($i==1)echo "<br>";
    else echo "*<br>";
}

for($i=4; $i>=1; $i--){
    for($j=5; $j>$i; $j--){
        echo " ";
    }
    echo "*";
    for($j=1; $j<($i-1)*2; $j++){
        echo " ";
    }
    if($i==1)echo "<br>";
    else echo "*<br>";
} ?></pre>

Note: if your target is console and PHP-CLI, don't put the <pre/> tag, omit the end of PHP tag (?>) and replace all <br/> tags with \n.