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.
Comments
I like when the code is
I like when the code is readable (even if it takes a bit more time)
Asicgroup
good article. i I know
good article. i I know several "experienced" programmers who are always complicating the task. they write 3 pages instead of 30-40 lines.
Marc
There's nothing unreadable
There's nothing unreadable about them when you just see one or two of them. Its the overall code style that it can lead to in inexperienced hands which then reflects poorly on PHP as a language. I have no real problems with 1-3, in face I use them on occasion, but usually encapsulated within a function or class that someone else isn't likely to see or care. Also, I didn't slam Alex's advice, I just pointed out that writing less code does not automatically mean you write "better" code, albeit for my definition of better.
Barton
I disagree with a few things
The less code example on 1 is simply not good advice (although the final is good). It is far harder to read. Although fewer lines is a good thing, you should not sacrifice readable code for it.
The final if statement in 2 is ok for small things, but what if you need to do a bunch of processes if age < 16? You will have to reformat the if or make it really hard to read. Leaving the chance of a bug thus taking more time. Better just to use a regular if. Shorthand if's are almost never a good idea.
3 Is very circumstantial. In the instance you gave, for is better. But the purpose of a while loop is looping though something an unknown number of times. For is for when you know how many times you will be going though.
Logical operators
Please keep in mind &&/|| and and/or are not always interchangeable; they have different precedences. If you're looking to string expressions together like in #1 above, and/or are usually what you want.
The article kind of implies they are just aliases, but they are distinct operators.
I like the ternary operator
It's more compact for simple constructs and allows me to avoid using temporary variables. However, I can go overboard sometimes as in this redirect function.
Good, but not always possible
Hi Alex,
Thanks for calling me lazy. It's not obvious to much of my collegues, but doing a little as possible to achief as much as possible is still my drive.
I like your examples, however this approach is not always possible. I don't like to call something like a log function, because I like to choose how to solve a problem per case. Using exceptions is excelent for this, however you can't use 'or throw', so you need to use temporary variables.
As with the function 'a' returning an item from an array, using and is simpler and faster. There have been many votes on this to allow the array aproach on a function output, but the conservatives have managed to keep this out of PHP.
I really like your point 5. Please people read the f**king manual. I so often see large bits of code, which can be written in 1 or 2 lines.
http://blog.adaniels.nl
Hi, Like you pointed out in
Hi,
Like you pointed out in 6., writing less code at the expense of readability is not really a good choice. You'll find no framework coding standard that lets you write if condition and body as a one-liner because nobody wants to maintain such spagetthi-code ;) So I really don't like the tipps 1-3.
Writing less code is not about writing less lines. It's about avoiding copy-and-paste programming and no formatting-paradim but more a question of programming skills.
As with the function 'a'
As with the function 'a' returning an item from an array, using and is simpler and faster. There have been many votes on this to allow the array aproach on a function output, but the conservatives have managed to keep this out of PHP.
used replica rolex watches
PHP is sexy
Nice article...I've always thought it was ridiculous to write 20 lines of code for something that can be done in 2. I'm guilty of it though...
v-nessa.net
I liked tips 1-3
I was actually looking for the correct syntax of the ways to write the code as mentioned in those tips. More about it here...
http://oksoft.blogspot.com/2007/11/6-php-coding-tips-by-alex.html
I agree, 1-3 is
I agree, 1-3 is great.
----------------------------------
Email - labs.beanz[at]gmail.com
AIM - dolphinlabz
Yahoo - zubu1980
How To Petition