phploopsascii-art

Print pattern of asterisks with n per line, decrementing to 1, then back to n


If the input is 3 then the output should be

***
**
*
**
***

In the same way, if the accepted values is 5 then the output should be

*****
****
***
**
*
**
***
****
*****

This is what I've done 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";
}
?>

Solution

  • What's with the nested for loops?

    $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 one more for loop:

    $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>';
    

    Note that this code wouldn't be valid with $maxNum < 1.

    To fetch a value from the user replace the $maxNum line with...

    $maxNum = $_GET['maxNum'];
    

    and load the page using scriptname.php?maxNum=5