I have been participating in a number of PHP code golf challenges recently and some of the techniques that are used to read data from a file such as fopen() and fread() or file_get_contents() really give my code a beating on the char count. Especially the methods provided for reading in command line input.

My question is, what is the fastest way (least keystrokes) to read and write to the contents of a file, and what is the fastest way (least keystrokes) to read a line from the prompt?

(Note: As this is code golf, I can't use any external libraries.)


You can read a line from STDIN in 13 characters:


as seen here.

Reading from a file:


returns an array of lines of the file.

Using fputs instead of fwrite will save a character on writing, but I can't think of a shorter way than:

fputs(fopen('filename','w')); //use 'a' if you're appending to a file instead of overwriting

which is marginally shorter than:

  • \$\begingroup\$ Great! Do you have any advice on writing to a file? \$\endgroup\$ – Dan Prince May 3 '12 at 13:28
  • \$\begingroup\$ @DanPrince I've added a bit on writing. Can't see anything shorter on that at the moment though. \$\endgroup\$ – Gareth May 3 '12 at 13:35

Depending on the input format, fgetcsv and fscanf can often be byte savers as well.

For example, assume each line of your input consists of two space separated integers. To read these values into an array, you could use one of:

$x=split(' ',fgets(STDIN)); // 27 bytes
$x=fgetcsv(STDIN,0,' ');    // 24 bytes
$x=fscanf(STDIN,'%d%d');    // 24 bytes

Or if you wanted to read each of them into a different variable:

list($a,$b)=split(' ',fgets(STDIN)); // 36 bytes
list($a,$b)=fgetcsv(STDIN,0,' ');    // 33 bytes
fscanf(STDIN,'%d%d',$a,$b);          // 27 bytes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.