PHP golfing tips: Reading/writing files and the CLI

8

1

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.)

Dan Prince

Posted 2012-05-03T09:41:54.450

Reputation: 1 467

Answers

6

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');

Gareth

Posted 2012-05-03T09:41:54.450

Reputation: 11 678

Great! Do you have any advice on writing to a file? – Dan Prince – 2012-05-03T13:28:24.243

@DanPrince I've added a bit on writing. Can't see anything shorter on that at the moment though. – Gareth – 2012-05-03T13:35:32.423

6

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

primo

Posted 2012-05-03T09:41:54.450

Reputation: 30 891

0

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!

More information: https://www.php.net/manual/en/reserved.variables.argv.php

Night2

Posted 2012-05-03T09:41:54.450

Reputation: 5 484