'PHP Displaying a number of asterisks depending on the number given in the input field

What I want to accomplish is to display an asterisk or asterisks () depending on the number I input. For example if I input 2, the form will display 2 asterisks (*). In my code, I don't think string concatenation is not the right way to do it as I didn't get the result I wanted. I use a for loop. I'd appreciate if you can tell me how to code it the right way or if the for loop is wrong in this situation. Here's the code so far.

    <?php

    $number = $star = '';

    if (isset($_POST['submit'])) {

    $number = (int)$_POST['number'];
    $star = '*';

    for ($i = 0; $i < $number; $i++) {
    $star .= $star;
    }
    }
    ?>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Star</title>
    </head>
    <body>
    <!--Form-->
    <form id="form" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
    <label for="number">Enter number</label>
    <input id="number" type="number" name="number" size="3" maxlength="3" required>
    <input type="text" readonly="readonly" value="<?php echo $star; ?>">
    <input type="submit" name="submit" value="Display">
    </form>
    </body>
    </html>


Solution 1:[1]

How about str_repeat()

$star = str_repeat("*", $number);

With your current code you will always get more asterixes (as mentioned in the comments by @AeJey) because you are starting with one *, you join it with itself getting **, then again join with itself getting ****...

Solution 2:[2]

@Unamata Sanatarai str_repeat() works nice in this situation, so use that instead.

Don't forget some error checking:

<?php
if (isset($_POST['submit'])) {

    $number = (int) $_POST['number'];

    if ($number > 0) {
        $star = str_repeat("*", $number);
    } else {
        $star = "Enter number greater than zero!";
    }
}
?> 

Hope this helps..

`

Solution 3:[3]

Don't concatenate $star on $star ($star .= $star;). Choose another variable - $out .= $start and output that instead.

Or you could use the string padding function to repeat the wanted number of times.

$number = (int) $_POST["number"];
$out = str_pad("", $number, "*");

Solution 4:[4]

Your printed asterisks are doubleing in string length each iteration because you are concatenating the whole cached string onto itself.

Instead only add a single character to the cached string on each iteration.

Code: (Demo)

$number = 5;
$star = '*';
$stars = $star;
for ($i = 0;
     $i < $number;
     ++$i, $stars .= $star
) {
    echo "$stars\n";
}

Output:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Unamata Sanatarai
Solution 4 mickmackusa