Home > php教程 > php手册 > body text

php输出金字塔2种方法

WBOY
Release: 2016-05-26 08:21:05
Original
2410 people have browsed it

下面给大家总结了两种实现金字塔打印的方法,一种是利用了自定义函数,另一种是利用了for循环了,其实两都用到了只是前者高级一些吧.

自定义函数实现金字塔,代码如下:

<?php
/** 
 * 金字塔
 * string fun_py(int $rows = 9, bool $sort=true)
 * $rows 表示行数 必须为整数 并且必须在1-20之间
 * $sort 表示排序 true表示正序 FALSE表示倒序
 */
function fun_py($rows = 9, $sort = true) {
    if ($rows < 1 || $rows > 20) {
        return "必须在1-20之间";
    }
    if ($rows != (int)($rows)) {
        return &#39;行数 必须为整数&#39;;
    }
    $str = "";
    if ($sort) {
        for ($i = 1; $i <= $rows; $i++) {
            $str.= &#39;<br/>&#39;;
            for ($j = 1; $j <= $i; $j++) {
                if ($j == 1) {
                    for ($k = 1; $k <= ($rows - $i); $k++) {
                        $str.= &#39;&nbsp&#39;;
                    }
                }
                $str.= &#39;*&#39; . &#39;&nbsp&#39;;
            }
        }
    } else {
        for ($i = $rows; $i >= 1; $i--) {
            $str.= &#39;<br/>&#39;;
            for ($j = 1; $j <= $i; $j++) {
                if ($j == 1) {
                    for ($k = 1; $k <= ($rows - $i); $k++) {
                        $str.= &#39;&nbsp&#39;;
                    }
                }
                $str.= &#39;*&#39; . &#39;&nbsp&#39;;
            }
        }
    }
    return $str;
}
echo fun_py(9, false);
Copy after login

下面再实现个金字塔形状物,通用也是用到for循环,代码如下:

<?php
/** 
 金字塔正序
 *
 */
for ($a = 1; $a <= 10; $a++) {
    for ($b = 10; $b >= $a; $b--) {
        echo "&nbsp";
    }
    for ($c = 1; $c <= $b; $c++) {
        echo "*" . "&nbsp";
    }
    echo "<br />";
}
Copy after login


同样想让这个金字塔倒立起来呢,代码如下:

<?php
/** 
 金字塔玩倒立
 *
 */
for ($a = 10; $a >= 1; $a--) {
    for ($b = 10; $b >= $a; $b--) {
        echo "&nbsp";
    }
    for ($c = 1; $c <= $b; $c++) {
        echo "*" . "&nbsp";
    } //开源代码phprm.com
    echo "<br />";
}
Copy after login


本文地址:

转载随意,但请附上文章地址:-)

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!