skip to Main Content

I want to repeat echo("text!") as often as $variable in PHP.

So, let’s say:

$variable = 3;

Now I want the output to be:

text! text! text!

How do I code this as a loop? I’ve tried the following but the loop isn’t stopping as it should:

$variable=readline(1,10)
for ($variable>0; $variable<11; $++){
echo("text!"); }

2

Answers


  1. Either use loop or str_repeat:

    $variable = 3;
    
    for ($i = 1; $i <= $variable; $i++) {
        echo 'text! ';
    }
    

    or

    echo str_repeat('text! ', $variable);
    
    Login or Signup to reply.
  2. One of the ways: use a function

    (e.g. echotest($var1, $var2) which use a for loop to do the job)

    <?php
    $variable=3;
    $string="text ! ";
    
    echotest($string, $variable);
    
    function echotest($var1, $var2){
     for ($i=0; $i<$var2; $i++) { echo $var1; }
    }
    ?>
    

    You may simply change $variable (say change to 3000) and $string (say change to "Covid-19 ended !! " and see the changed result.

    See this sandbox link :

    http://www.createchhk.com/SOanswers/testso10oct2022b.php

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search