Search code examples
phprecursioncounterrepeat

PHP - Two lines of code to print string multiple times


I need some guidance with a exercise I was set as part of my PHP class. I've tried many different methods but none that satisfy the requirements. The task is to do the following:

Prerequisite :

  1. Without using any variation of a loop
  2. Without any variation of string repeat
  3. Without string join function
  4. Without the require statement
  5. Using only 4 lines of code

    • It's worth noting that each statement must be on it's own line and the <?php, ?> tags count as one line each.

Output: print the following text 200 times

“All work and no play makes jack a dull boy.”

I'm assuming it requires the use of a while loop but I've exhausted my knowledge of PHP and simply can't come up with a solution. I'm not necessarily looking for the answer just to be pointed in the right direction.

Thank you.


Solution

  • Not sure if I got it or not, but heres my try...

    function printsth ($count) {
        echo $count++, "All work and no play makes jack a dull boy.<br>", $count <= 200 ? printsth($count++) : "";
    }
    printsth(1);
    

    cleaner version

    function printsth ($count) {
        echo "All work and no play makes jack a dull boy.<br>", $count++ < 200 ? printsth($count++) : "";
    }
    printsth(1);