Print a star in PHP that takes one value and prints something like this
If the input signal is 3, the output should be
***
**
*
**
***
Likewise, if the accepted values are 5, the output should be
*****
****
***
**
*
**
***
****
*****
This is what I did, but its not correct
<?php
echo "<pre>";
for ($row = 1; $row <= 5; $row++)
{
for ($col = 1; $col <= 6 - $row; $col++)
{
echo '*';
}
echo "\n";
}
for ($row = 1; $row <= 5; $row++)
{
for ($col = 1; $col <= $row; $col++)
{
echo '*';
}
echo "\n";
}
?>
source to share
What about nested loops for
?
$lineBreak = "\r\n"; // This may need to be <br /> if carriage returns don't show in <pre>
$maxNum = 5;
echo '<pre>';
for ($i = $maxNum; $i > 0; $i--) {
echo str_repeat('*', $i) . $lineBreak;
}
for ($i = 2; $i <= $maxNum; $i++) {
echo str_repeat('*', $i) . $lineBreak;
}
echo '</pre>';
For fun, to eliminate another loop for
:
$lineBreak = "\r\n";
$maxNum = 5;
$out = '*';
for ($i = 2; $i <= $maxNum; $i++) {
$out = str_repeat('*', $i) . $lineBreak . $out . $lineBreak . str_repeat('*', $i);
}
echo '<pre>' . $out . '</pre>';
Please note that this code is not valid with $maxNum < 1
.
To get the value from the user, replace the string $maxNum
with ...
$maxNum = $_GET['maxNum'];
and load the page with scriptname.php?maxNum=5
source to share
One-liner for you: p
echo implode("\n",array_map(function($n) {return str_repeat("*",$n);},array_merge(range($input,1),range(2,$input))));
Broken:
- Create a range of numbers from "input" to 1
- Create a range of numbers from 2 to "input" (prevents duplicate "1")
- Combine the two ranges, resulting in a down-down list
- Replace each element in the array with the appropriate number of stars
- Glue them onto new lines.
Note what you may need <br />
instead \n
for browser output.
source to share