How can we echo the variable multiple times in PHP?

 The very simple PHP interview question always get asked to PHP Fresher in a job interview.



And the question you already see in a title is: How can we echo the variable multiple times in PHP?

Answer:

You can do it by multiple ways.

Example:

<?php

$my_variable = "echo me 7 times";

//how to echo the $my_variable 7 times

?>


Option 1:

echo it 7 times manually/individually as

<?php

$my_variable = "echo me 7 times";

echo $my_variable . "<br/>";

?>


Option 2:

Use for loop as:

<?php

$my_variable = "echo me 7 times";

for($i=0;$i<7;$i++){

  echo $my_variable . "<br/>";

}

?>


Option 3:

Use str_repeat() string function as:

<?php

$my_variable = "echo me 7 times";

echo str_repeat($my_variable , 7);

echo "<br/>";

?>

In this way you can print the variable multiple times in PHP. 

Now you can try above solutions on your machine or run PHP examples online.