Code Golfing Tips

Navigation

Recent site activity

PHP

The interpreter

<? might be enough to trigger the interpreter, instead of <?php.  Either the last ; or the ?> at the end can be skipped. Remember that any text outside <? ?> will be printed to stdout.

Strings

You can sometimes ommit quotes for strings. For example print(hello) will print "hello". This only works if nothing else use the string as its name, and mainly for letters.

Variables and arrays

PHP doesn't require you to initialise variables or arrays before they are used. They will be treated as 0, '' or array(), depending on the context. This also counts for array entries. And remember that PHP doesn't really have arrays, they are actually hash tables, meaning the indexes can have gaps and so on.

Stdin

Reading from standard in can be done in a few ways, shortest depending on context.

To read everything, including newlines, as a long string, use:
fread(STDIN,1e4)
1e4 means 10000, and should be enough. If you are reading less than 100 characters, use 99 instead of 1e4.

To read a line, use:
fgets(STDIN)
This will return the newline at the end aswell.

To read a char, use:
fgetc(STDIN)

To read a list of separated values, there is a special function:
fgetcsv(STDIN)
This returns an array of the values of one line, where the values are separated by a comma.
But you can also specify the delimiter, making it shorter than spliting on space with another function: 
explode(' ',fgets(STDIN))
split(' ',fgets(STDIN))
fgetcsv(STDIN,0,' ')