代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="#" method="post">
<input type="number" name="n" placeholder="請(qǐng)輸入要打印的行數(shù)"><br/>
<input type="submit" name="pyramid" value="金字塔">
<input type="submit" name="diamond" value="空心菱形">
</form>
<?php
error_reporting(E_ALL&~E_NOTICE);
$n = $_POST['n'];
$pyramid=$_POST['pyramid'];
$diamond=$_POST['diamond'];
if (is_numeric($n)) {
if ($n > 0) {
if (isset($pyramid)) {//打印金三角
for ($i = 1; $i <= $n; $i++) {//行數(shù)
for ($j = 0; $j < $n - $i; $j++) {//打印空格
echo '<span style="color: #fff;">*</span>';//echo " ";
}
for ($k = 1; $k <= ($i - 1) * 2 + 1; $k++) {//打印星星
echo '*';
}
echo '<br/>';
}
} elseif (isset($diamond)) {//打印空心菱形
//菱形的上半部
for ($i = 1; $i <= $n; $i++) {//行數(shù)
for ($j = 1; $j <= $n - $i; $j++) {//打印空格
echo '<span style="color: #fff;">*</span>';
}
for ($k = 1; $k <= ($i - 1) * 2 + 1; $k++) {//打印星星
if ($k == 1 || $k == ($i - 1) * 2 + 1) {
echo "*";
} else {
echo '<span style="color: #fff;">*</span>';
}
}
echo "<br/>";
}
//菱形的下半部
for ($i = $n - 1; $i >= 1; $i--) {
for ($j = 1; $j <= $n - $i; $j++) {
echo '<span style="color: #fff;">*</span>';
}
for ($k = 1; $k <= ($i - 1) * 2 + 1; $k++) {
if ($k == 1 || $k == ($i - 1) * 2 + 1) {
echo "*";
} else {
echo '<span style="color: #fff;">*</span>';
}
}
echo "<br/>";
}
}
} else {
echo '請(qǐng)輸入正整數(shù)';
}
}
?>
</body>
</html>
結(jié)果如下: