logo CodeStepByStep logo

reverse_lines

Language/Type: PHP recursion streams file input

Write a recursive function named reverse_lines that accepts a file name $filename as its parameter and prints the lines of that file in reverse order. For example, if an input file named poem.txt contains the following text:

Roses are red,
Violets are blue.
All my base
Are belong to you.

Then the call of reverse_lines("poem.txt"); should produce the following console output:

Are belong to you.
All my base
Violets are blue.
Roses are red,

You may assume that the input file exists and is readable.

Constraints:

  • Your function must be recursive and must not use loops.
  • Your solution must not change the contents of the file data.
  • Your solution should read the file only once, not make multiple passes over the file data. You may find a helper function helpful for meeting this requirement, passing in an array of lines from the read file argument to a helper function which implements the recursive behavior.
Function: Write a PHP function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.