Home > database >  How do I repeat text with a php loop based on a $variable?
How do I repeat text with a php loop based on a $variable?

Time:10-11

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!"); }

CodePudding user response:

Either use loop or str_repeat:

$variable = 3;

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

or

echo str_repeat('text! ', $variable);

CodePudding user response:

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

  • Related