Home  >  Article  >  php教程  >  php输出金字塔的2种实现方法

php输出金字塔的2种实现方法

WBOY
WBOYOriginal
2016-06-06 20:15:501828browse

这篇文章主要介绍了php输出金字塔的2种实现方法,涉及循环语句的调用技巧,对于php的学习有一定的借鉴价值,需要的朋友可以参考下

本文实例讲述了php输出金字塔的2种实现方法。分享给大家供大家参考。具体分析如下:

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

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

复制代码 代码如下:

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


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

复制代码 代码如下:

/**
金字塔正序
**/
for($a=1;$a  for ($b=10;$b>=$a;$b--){
    echo " ";
  }
 for ($c=1;$c    echo "*"." ";
 }
 echo "
";
}
?>


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

复制代码 代码如下:

/**
金字塔玩倒立
**/
for($a=10;$a>=1;$a--){
 for ($b=10;$b>=$a;$b--){
    echo " ";
  }
 for ($c=1;$c    echo "*"." ";
 }
 echo "
";
}
?>

希望本文所述对大家的PHP程序设计有所帮助。

Statement:
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