php php中的星号金字塔

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13250725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:02:44  来源:igfitidea点击:

Pyramid of asterisks in php

php

提问by arjay0601

I am having problem creating a pyramid of asterisk. Please see my code.

我在创建星号金字塔时遇到问题。请看我的代码。

  <?php

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

    ?>

Result:

结果:

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

My question is how I am going to make that like.

我的问题是我将如何做到这一点。

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

回答by Orme

<pre><?php

$n = $i = 5;

while ($i--)
    echo str_repeat(' ', $i).str_repeat('* ', $n - $i)."\n";

?></pre>

回答by Deep Dey

use the same program within <center> </center>tag ! like:

<center> </center>标签内使用相同的程序!喜欢:

<center>
<?php

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

?>
</center>

回答by Henrik Peinar

Use HTML whitespace character to procude the whitespaces: &nbsp;

使用 HTML 空格字符来产生空格:  

So something like this:

所以像这样:

<?php
// pyramid height
$height = 5;

for($i=1;$i<=$height;$i++){

    for($t = 1;$t <= $height-$i;$t++)
    {
        echo "&nbsp;&nbsp;";
    }

    for($j=1;$j<=$i;$j++)
    {
        // use &nbsp; here to procude space after each asterix
        echo "*&nbsp;&nbsp;";
    }
echo "<br />";
}

?>

回答by silly

try this

尝试这个

$height = 5;

$space = $height;
for($i = 1; $i <= $height; $i++) {
    echo str_repeat(' ', --$space);
    for($j=1;$j<=$i;$j++){
        if($j > 1) {
            echo ' ';
        }
        echo '*';
    }
    echo '<br />';
}

回答by Chris

create_pyramid("*", 5);

function create_pyramid($string, $level) {
    echo "<pre>";
    $level = $level * 2;
    for($i = 1; $i <= $level; $i ++) {
        if (!($i % 2) && $i != 1)
            continue;   
        print str_pad(str_repeat($string, $i),($level - 1) * strlen($string), " " , STR_PAD_BOTH);
        print PHP_EOL;
    }
}

From linkposted above by Baba

来自Baba上面发布的链接

回答by user3359698

$n = 5;
$i = 0;

for($i=1; $i<=$n; $i++){

    echo "<pre>";   
    echo str_repeat("&nbsp;", $n-$i);
    echo str_repeat("#&nbsp;", $i);
}