打印特殊字符数组 - PHP

时间:2015-07-02 12:12:53

标签: php html

我正在尝试创建一个名为draw_stars()的函数,它接受一个数字数组并回显*。

    For example:

    $x = array(4, 6, 1, 3, 5, 7, 25);
    draw_stars(x) should print the following on the screen/browser:

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

到目前为止,这是我的代码:

$x = array(4, 6, 1, 3, 5, 7, 25);
        function draw_stars($items){
            foreach ($items as $item) {
                for($i=0; $i<=$item; $i++){
                    echo '* <br>';
                }
            }
        }

        $output = draw_stars($x);
        echo $output;

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

开箱即用

   <?php
       $x = array(4, 6, 1, 3, 5, 7, 25);
       foreach($x as $num) {
          echo str_repeat("*", $num).'<br>';
       }

这是一个函数

  <?php
       function draw_stars(array $x, $star='*', $newline='<br>') {
           $return = '';
           foreach($x as $num) {
             $return.=str_repeat($star, $num).$newline;
           }
           return $return;
       }
       $x = array(4, 6, 1, 3, 5, 7, 25);
       echo draw_stars($x);
       echo draw_stars($x,'_'); // with an otherstring example

答案 1 :(得分:0)

似乎你在每个星星之后打印一个换行符,这显然是错误的。此外,您的功能不会返回任何内容。我稍微修改了你的代码---现在应该可以了。

        $x = array(4, 6, 1, 3, 5, 7, 25);
        function draw_stars($items){
            $out = "";
            foreach ($items as $item) {
                for($i=0; $i<=$item; $i++){
                    $out .= '*';
                }
                $out .= '<br>';
            }
            return $out;
        }

        $output = draw_stars($x);
        echo $output;

答案 2 :(得分:0)

<?php
$x = array(4, 6, 1, 3, 5, 7, 25);
function draw_stars($items){
    foreach ($items as $item) {
        for($i=0; $i<$item; $i++){
            echo '*';
        }
        echo '<br />';
    }
}

draw_stars($x);
?>

在这里,您也可以使用&#39;&lt; =&#39;你有,你总会再打印一个你真正想要的开始,因为$ i从0开始。
而且你现在在每次开始后打印一个休息时间,应该是在启动线之后。

相关问题