6 PHP coding tips to write less code

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.

Its the overall code style


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

Great blog, Here's an example


Great blog,
Here's an example of PHP 5's (good) habit have passing objects by reference:

$cart = get_cart(); // Get a genuine $cart object, not just a copy.
$cart->lines[0]->qty = 2; // Make changes to the cart object that
// came from get_cart(). Now the cart object
// inside get_cart() will have that change too.

To accomplish the same with PHP 4, you would have to do something like this:

$cart = get_cart(); // Now I have a copy of the $cart object
$cart->lines[0]->qty = 2;
save_cart($cart); // Need to explicitly save the cart

OR

$cart =& get_cart(); // Note the '&'. Now I have THE $cart object
$cart->lines[0]->qty = 2;

fast pay day loans

Php coding


Alex,
Thanks for the php coding tips. I do a lot of php websites, and trust me any coding that can save time, especially with variable names, it is very helpful. Now if someone else has to eventually do anything with the site, that can be another story, but if you are the only one coding the site, then these tips are great. Thanks.

Barstools::Indiana Web Design

Some sensible tips there.


Some sensible tips there. It's all about legibility AND writing "concise" code - it's not either/or - you can achieve both goals.

Diamond Blades

Hi Alex, Do you have any tips


Hi Alex,

Do you have any tips on best practices to learn PHP? I tried learning before (about a year ago) but found it difficult to pick up. Would you recommend reading guides or just writing simple PHP scripts to get the hang of it?

Tim
Mattress reviews

Agree with comments - don't


Agree with comments - don't be lazy programmers, comment your code, and put the comments in plain English, that's what they're there for - to be understood!

Reading Festival Camping Tickets

Ultimately code should be


Ultimately code should be self-describing. Comments are there to clarify, not be a substitute for, understanding the code.

Gardening and Landscaping Directory

Useful info since so much


Useful info since so much code needs to be maintained by OTHER people reading your code in the future. It saves a lot of time if your code is easy to understand.

Husqvarna Saws

tip #1


use ruby!

You should always prefix


You should always prefix variables with its type e.g. intNoOfApples or arrArrayOfNumbers

I like self-descriptive variables - my philosophy is this : try to let the code comment on itself, rather than accompany every line of code with a written comment

Diamond Core Drilling

Well its perfectly fine for


Well its perfectly fine for someone like me who is too lazy to write codes . thanks .

online sportsbook|| Website builder

Reply


"PHP: Easy to lern, hard to understand completely"
Physics Assignment | Buy Assignment

thanks alex . yes php is a


thanks alex . yes php is a good and very popular language now . i am member in various php forums and i m learning it . and i m a bit lazy as well lol .
website builder ||live football

Reply


This tip is useful to "lazy" developers who do not even think about variable names.
Finance Dissertation | History Dissertation | Sports Dissertation

Very good article


Thanks for this article.
I also use technique 1 and 2 very often.
They are very nice and sexy examples of PHP.
I also prefer "for" to "while" and your example brings this to a new level i haven't thought of yet ;-)
There is only one word for 4: Great!
5 "PHP: Easy to lern, hard to understand completely"
6 As i always teach in my lectures: "Don't be lazy but don't do more as needed"
thanks a lot, tienod

Re:


In principle, if on this website will be written in same topics and more, I will read it. funny christmas gifts

code


hello sir,
// 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!';

}
this code is not working properly
seo

Re: code


Please argument your point.

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.

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

Shorter codes are always


Shorter codes are always better in any language, especially if it is a larger project being made by several people... Depeche Mode ticket

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

PHP


A having shorter code seems a good idea but if you need anyone else to look back and work with your code at any point it'll be a nightmare!

----------------------------------

kefalonia Holidays