What general tips do you have for golfing in PHP? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to PHP (e.g. "remove comments" is not an answer). Please post one tip per answer.
|
|
Understand how variables and whitespace interact with PHP's language constructs. In my (admittedly short) time golfing, I have found that PHP's language constructs (e.g. echo, return, for, while, etc) behave in a less-than-intuitive way when interacting with variables and whitespace.
Keep in mind, though, that variables before language constructs require a space after, as in the following example:
Because |
||||
|
|
|
Use strings wisely. This answer is two-fold. The first part is that when declaring strings, you can utilize PHP's implicit conversion of unknown constants to strings to save space, e.g:
The is that sometimes, it may be space effective to set a variable to the name of an often used function. Normally, you might have:
But when golfing, this can be shortened easily to:
With only two instances of "preg_match", you're only saving a single character, but the more you use a function, the more space you will save. |
||||
|
|
|
You don't always need to write out conditional checks. For example, some frameworks use this at the top of their files to block access:
Or in normal functions
instead of
|
||||
|
|
|
Learn a large subset of the library functions. PHP's library is pretty huge and provides a ton of convenient functions that can greatly shorten various tasks. You could just search every time you try to do something, but beyond wasting time you might not find anything that matches your particular search. The best way is just to get familiar with the library and memorize function names and what they do. |
|||||||||||
|
|
Regarding file I/O: Linking to another related question, the answers to which fit here. |
||||
|
|