October 1, 2008

6 tips to write less code php

PHP is a good language, but there are always surprises. And today I've seen an interesting approach in Arnold Daniels's blog. He talks about temporary variables in PHP. This tip is useful to "lazy" developers who do not even think about variable names. They may prefer magic names like ${0} and 0 is good enough variable name, why not...

But I'm even more lazy then Arnold and sure that when there is no variable, then there is no problem. So here are a few tips that can make your code shorter and harder to read :-)

1. Use || (or) and && (and) operations instead of if.
// A lot of code
$status = fwrite($h, 'some text');
if (!
$status) {
log('Writing failed');

// Less code
${0} = fwrite($h, 'some text');
if (!${
0}) log('Writing failed');

// Even less code
fwrite($h, 'some text') or log('Writing failed');
2. Use ternary operator.
// A lot of code
if ($age < 16) {
$message = 'Welcome!';
} else {
$message = 'You are too old!';

// Less code
$message = 'You are too old!';
if (
$age < 16) {
$message = 'Welcome!';

// Even less code
$message = ($age < 16) ? 'Welcome!' : 'You are too old!';

3. Use for instead of while.
// A lot of code
$i = 0;
while (
$i < 100) {
$source[] = $target[$i];
$i += 2;

// less code
for ($i = 0; $i < 100; $source[] = $target[$i+=2]);

4. In some cases PHP requires you to create a variable. Some examples you can find in my PHP fluent API tips article. Another example is getting array element when array is returned by the function.
$ext = pathinfo('file.png')['extension'];

// result: Parse error: syntax error, unexpected '[' in ... on line ...
To handle all these situation you can create a set of small functions which shortcuts frequently used operations

// returns reference to the created object
function &r($v) { return $v; }

// returns array offset
function &a(&$a, $i) { return $a[$i]; }

5. Explore the language you use. PHP is very powerful and has a lot of functions and interesting aspects of the language which can make your code more efficient and short.

6. When it is better to write more and then read the code easily, do not be lazy.
Spend a few seconds and write a comment and more readable construction. This is the only tip in this list that really can save hours, not minutes.

No comments: