PHP golfing tips: Reading/writing files and the CLI
You can read a line from STDIN
in 13 characters:
fgets(STDIN);
as seen here.
Reading from a file:
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');
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