# PHP golfing tips: Reading/writing files and the CLI

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:

fgets(STDIN);


as seen here.

file('filename')


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:

file_put_contents('filename');

• Great! Do you have any advice on writing to a file? May 3 '12 at 13:28
• @DanPrince I've added a bit on writing. Can't see anything shorter on that at the moment though. 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  ### To read non-physical files (read input) If you have a single line input, use -F and $argn to read from STDIN. This is only 5 bytes and a lot shorter than other methods.

Example: Try it online!

Basically -F runs your code once for every single line of the input and fills $argn with string of that input line. More information: https://www.php.net/manual/en/features.commandline.options.php If you have a multi line input, use $argv. $argv is an array which starting from index 1 contains all arguments you pass to your code. So you can use $argv[1] and so on, which is only 8 bytes. You can pass multiple arguments too and loop on them with for(;$a=$argv[++\$i];) which usually is shorter than other methods.

Example 1: Try it online!

Example 2: Try it online!