[英]How to print this pattern using PHP?
How to print this Pattern?如何打印此图案?
$number = 5;
for ($i=1; $i <= $number ; $i++) {
for ($j=$i; $j >= 1;$j--){
echo "0";
}
echo "\n";
}
Prints印刷
0
00
000
0000
00000
I've tries like this, but i'm confused to print star and Zero char我试过这样,但我很困惑打印明星和零字符
for ($i=1; $i <= $number ; $i++) {
$sum = 0;
for ($j=$i; $j >= 1;$j--){
$sum +=$j;
}
echo $i ." => " .$sum ."\n";
}
Prints印刷
1 => 1
2 => 3
3 => 6
4 => 10
5 => 15
You can use str_repeat
to generate the strings of required length.您可以使用
str_repeat
生成所需长度的字符串。 Note that for triangular numbers (1, 3, 6, 10, 15, ...)
you can generate the i
'th number as i(i+1)/2
:请注意,对于三角数
(1, 3, 6, 10, 15, ...)
您可以生成第i
个数为i(i+1)/2
:
$number = 5;
for ($i = 1; $i <= $number; $i++) {
echo str_repeat('*', $i * ($i + 1) /2) . str_repeat('0', $i) . PHP_EOL;
}
Output: Output:
*0
***00
******000
**********0000
***************00000
Demo on 3v4l.org 3v4l.org 上的演示
For a more literal generation of the triangular part of the output (ie sum of the numbers from 1 to i
), you could use this code which adds $i
*
's and 1 0
to the output on each iteration:为了更直接地生成 output 的三角形部分(即从 1 到
i
的数字总和),您可以使用此代码在每次迭代时将$i
*
和 1 0
添加到 output 中:
$line = '';
$number = 5;
for ($i = 1; $i <= $number; $i++) {
$line = str_repeat('*', $i) . $line . '0';
echo $line . PHP_EOL;
}
Output: Output:
*0
***00
******000
**********0000
***************00000
Here is another way, which uses a more literal reading of the replacement logic.这是另一种方式,它使用替换逻辑的更字面理解。 Here, I form each subsequent line by taking the previous line, and adding the line number amount of
*
to the *
section, and then just tag on a new trailing zero.在这里,我通过取上一行并将
*
的行号数量添加到*
部分来形成每个后续行,然后只标记一个新的尾随零。
$line = "*0";
$max = 5;
$counter = 1;
do {
echo $line . "\n";
$line = preg_replace("/(\*+)/", "\\1" . str_repeat("*", ++$counter), $line) . "0";
} while ($counter <= $max);
This prints:这打印:
*0
***00
******000
**********0000
***************00000
The number of zeros are equal to $i in the for loop.在 for 循环中,零的数量等于 $i。 So we just need to calculate the number of stars and then simply do a str_repeat
所以我们只需要计算星星的数量,然后简单地做一个 str_repeat
$count = 5;
for ($i=1; $i <= $count; $i++) {
$stars = 0;
for($j=1; $j <= $i; $j++) {
$stars = $stars + $j;
}
echo str_repeat('*', $stars).str_repeat('0', $i)."\n";
}
Output: Output:
*0
***00
******000
**********0000
***************00000
$line = '';
for ($i = 1; $i <= 5; $i++) {
$line = str_repeat('*', $i) . $line . '0'; // **str_repeat()** --> getting string length
echo $line . PHP_EOL; // **PHP_EOL** ---> represents the endline character.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.