Creating half a number pyramid in PHP with for loops

瘦欲@ 提交于 2019-12-22 01:16:27

问题


I was told to create half a pyramid in for loops using php that looks as follows:

54321
4321
321
21
1
This is what I had created so far but I have no idea how to go about creating the rest of the pyramid.

for ($iB = 5; $iB >=0; $iB--) {  
   echo $iB.'<br>';
}

回答1:


Use a nested for loop. Try this...

for ($iB = 5; $iB > 0; $iB--) {
    for($i = $iB; $i > 0; $i--){
        echo $i;
    }
    echo '<br />';
}



回答2:


In case someone decides not to use numbers for input, do

$str = '54321';
while( $str ) {
    echo $str . PHP_EOL; // use <br> if output is in html
    $str = substr( $str, 1 );
}


来源:https://stackoverflow.com/questions/25851836/creating-half-a-number-pyramid-in-php-with-for-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!