Smashing Magazine - we smash you with the information that will make your life easier. really.

10 Advanced PHP Tips To Improve Your Programming

Advertisement

Update (25.03.2009): this article contains some factual errors. Please read the rebuttal of this article instead of this article.

PHP programming has climbed rapidly since its humble beginnings in 1995. Since then, PHP has become the most popular programming language for Web applications. Many popular websites are powered by PHP, and an overwhelming majority of scripts and Web projects are built with the popular language.

Because of PHP’s huge popularity, it has become almost impossible for Web developers not to have at least a working knowledge of PHP. This tutorial is aimed at people who are just past the beginning stages of learning PHP and are ready to roll up their sleeves and get their hands dirty with the language. Listed below are 10 excellent techniques that PHP developers should learn and use every time they program. These tips will speed up proficiency and make the code much more responsive, cleaner and more optimized for performance.

1. Use an SQL Injection Cheat Sheet

Sql in 10 Advanced PHP Tips To Improve Your Programming
A list of common SQL injections.

SQL injection is a nasty thing. An SQL injection is a security exploit that allows a hacker to dive into your database using a vulnerability in your code. While this article isn’t about MySQL, many PHP programs use MySQL databases with PHP, so knowing what to avoid is handy if you want to write secure code.

Furruh Mavituna has a very nifty SQL injection cheat sheet that has a section on vulnerabilities with PHP and MySQL. If you can avoid the practices the cheat sheet identifies, your code will be much less prone to scripting attacks.

2. Know the Difference Between Comparison Operators

Php in 10 Advanced PHP Tips To Improve Your Programming
PHP’s list of comparison operators.

Comparison operators are a huge part of PHP, and some programmers may not be as well-versed in their differences as they ought. In fact, an article at I/O reader states that many PHP developers can’t tell the differences right away between comparison operators. Tsk tsk.

These are extremely useful and most PHPers can’t tell the difference between == and ===. Essentially, == looks for equality, and by that PHP will generally try to coerce data into similar formats, eg: 1 == ‘1′ (true), whereas === looks for identity: 1 === ‘1′ (false). The usefulness of these operators should be immediately recognized for common functions such as strpos(). Since zero in PHP is analogous to FALSE it means that without this operator there would be no way to tell from the result of strpos() if something is at the beginning of a string or if strpos() failed to find anything. Obviously this has many applications elsewhere where returning zero is not equivalent to FALSE.

Just to be clear, == looks for equality, and === looks for identity. You can see a list of the comparison operators on the PHP.net website.

3. Shortcut the else

It should be noted that tips 3 and 4 both might make the code slightly less readable. The emphasis for these tips is on speed and performance. If you’d rather not sacrifice readability, then you might want to skip them.

Anything that can be done to make the code simpler and smaller is usually a good practice. One such tip is to take the middleman out of else statements, so to speak. Christian Montoya has an excellent example of conserving characters with shorter else statements.

Usual else statement:

if( this condition )
{
$x = 5;
}
else
{
$x = 10;
}

If the $x is going to be 10 by default, just start with 10. No need to bother typing the else at all.

$x = 10;
if( this condition )
{
$x = 5;
}

While it may not seem like a huge difference in the space saved in the code, if there are a lot of else statements in your programming, it will definitely add up.

4. Drop those Brackets

Things in 10 Advanced PHP Tips To Improve Your Programming
Dropping brackets saves space and time in your code.

Much like using shortcuts when writing else functions, you can also save some characters in the code by dropping the brackets in a single expression following a control structure. Evolt.org has a handy example showcasing a bracket-less structure.

if ($gollum == 'halfling') {
$height --;
}

This is the same as:

if ($gollum == 'halfling') $height --;

You can even use multiple instances:

if ($gollum == 'halfling') $height --;
else $height ++; 

if ($frodo != 'dead')
echo 'Gosh darnit, roll again Sauron';

foreach ($kill as $count)
echo 'Legolas strikes again, that makes' . $count . 'for me!';

5. Favour str_replace() over ereg_replace() and preg_replace()

Replace in 10 Advanced PHP Tips To Improve Your Programming
Speed tests show that str_replace() is 61% faster.

In terms of efficiency, str_replace() is much more efficient than regular expressions at replacing strings. In fact, according to Making the Web, str_replace() is 61% more efficient than regular expressions like ereg_replace() and preg_replace().

If you’re using regular expressions, then ereg_replace() and preg_replace() will be much faster than str_replace().

6. Use Ternary Operators

Instead of using an if/else statement altogether, consider using a ternary operator. PHP Value gives an excellent example of what a ternary operator looks like.

//PHP COde Example usage for: Ternary Operator
$todo = (empty($_POST[’todo’])) ? ‘default’ : $_POST[’todo’]; 

// The above is identical to this if/else statement
if (empty($_POST[’todo’])) {
$action = ‘default’;
} else {
$action = $_POST[’todo’];
}
?>

The ternary operator frees up line space and makes your code less cluttered, making it easier to scan. Take care not to use more than one ternary operator in a single statement, as PHP doesn’t always know what to do in those situations.

7. Memcached

Memcached in 10 Advanced PHP Tips To Improve Your Programming
Memcached is an excellent database caching system to use with PHP.

While there are tons of caching options out there, Memcached keeps topping the list as the most efficient for database caching. It’s not the easiest caching system to implement, but if you’re going to build a website in PHP that uses a database, Memcached can certainly speed it up. The caching structure for Memcached was first built for the PHP-based blogging website LiveJournal.

PHP.net has an excellent tutorial on installing and using memcached with your PHP projects.

8. Use a Framework

Cakephp in 10 Advanced PHP Tips To Improve Your Programming

CakePHP is one of the top PHP frameworks.

You may not be able to use a PHP framework for every project you create, but frameworks like CakePHP, Zend, Symfony and CodeIgniter can greatly decrease the time spent developing a website. A Web framework is software that bundles with commonly needed functionality that can help speed up development. Frameworks help eliminate some of the overhead in developing Web applications and Web services.

If you can use a framework to take care of the repetitive tasks in programming a website, you’ll develop at a much faster rate. The less you have to code, the less you’ll have to debug and test.

9. Use the Suppression Operator Correctly

The error suppression operator (or, in the PHP manual, the “error control operator“) is the @ symbol. When placed in front of an expression in PHP, it simply tells any errors that were generated from that expression to now show up. This variable is quite handy if you’re not sure of a value and don’t want the script to throw out errors when run.

However, programmers often use the error suppression operator incorrectly. The @ operator is rather slow and can be costly if you need to write code with performance in mind.

Michel Fortin has some excellent examples on how to sidestep the @ operator with alternative methods. Here’s an example of how he used isset to replace the error suppression operator:

if (isset($albus))  $albert = $albus;
else                $albert = NULL;

is equivalent to:

$albert = @$albus;

But while this second form is good syntax, it runs about two times slower. A better solution is to assign the variable by reference, which will not trigger any notice, like this:

$albert =& $albus;

It’s important to note that these changes can have some accidental side effects and should be used only in performance-critical areas and places that aren’t going to be affected.

10. Use isset instead of strlen

Isset in 10 Advanced PHP Tips To Improve Your Programming
Switching isset for strlen makes calls about five times faster.

If you’re going to be checking the length of a string, use isset instead of strlen. By using isset, your calls will be about five times quicker. It should also be noted that by using isset, your call will still be valid if the variable doesn’t exist. The D-talk has an example of how to swap out isset for strlen:

A while ago I had a discussion about the optimal way to determine a string length in PHP. The obvious way is to use strlen().

However to check the length of a minimal requirement it’s actually not that optimal to use strlen. The following is actually much faster (roughly 5 times)

It’s a small change but, like all the tips we’ve covered today, adds up to quicker, leaner code.

(al)

Glen Stansberry is the editor at Web Jackalope, a blog about creative Web development.

Post Rating
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading ... Loading ...

Tags: ,

Advertising
  1. 1
    crypta
    November 18th, 2008 5:51 am

    great!!

  2. 2
    Akino
    November 18th, 2008 5:54 am

    Amazing…….

  3. 3
    Tilo
    November 18th, 2008 5:59 am

    nice article

  4. 4
    farz
    November 18th, 2008 6:02 am

    these are great although not using common brackets and universal indentation will just make it harder to read code

  5. 5
    Oliver
    November 18th, 2008 6:07 am

    Dropping the brackets is a great way to make your code less readable. It’s a stupid tip.

  6. 6
    Philip
    November 18th, 2008 6:12 am

    I don’t really agree with dropping brackets left and right. I’ve always been taught it’s good practice to use them, because you can easily see where the conditions/loops are when scanning your code. Same with the use ternary operators and other shorthands – people overuse them and it makes it nearly impossible to debug their code later down the road.

    Let me ask, has anybody really noticed a difference in speed/load with:
    $var = "my name is bob";
    compared to
    $var = 'my name is bob';
    I’ve never noticed a difference in speed myself, even with pretty high loads.

  7. 7
    matt
    November 18th, 2008 6:19 am

    I see some bad ideas here. Applying the techniques #4, #6 and #9 will result in lesser readable and maintainable code. A little sidenote concerning performance: It is better to write good code and use caching techniques to increase performance.

  8. 8
    lica
    November 18th, 2008 6:21 am

    Oh yeah, this article came just in time!! I needed the SQL Injection Cheat Sheet today!

  9. 9
    Montoya
    November 18th, 2008 6:23 am

    Some of these tips are micro-optimizations while others are universally useful. I want to add a couple things to the mix:

    - Upgrade your PHP installation to the latest version… currently it’s 5.2+. This way, you can be certain that your server has the latest bugfixes.
    - Use an opcode cacher, like APC, to speed up your execution time. Opcode cachers saved compiled versions of your scripts, so they don’t have to be compiled every time they are run. This will make any PHP site much faster.
    - Use the mysqli class that comes with PHP 5 instead of the old mysql. This allows you to do object-based queries with bound parameters, which prevents SQL injection by ensuring that every parameter will be checked and forced to be an integer or a string, and will then be contained within the query, even if they have quotation marks injected.

    But the most important tip I can share is, always be learning!

  10. 10
    kidsinhalf
    November 18th, 2008 6:24 am

    I don’t see a speed difference when choosing or . I would recommand using . Because in notepad++, the $var is good colored !

    Nice post.

  11. 11
    Xobb
    November 18th, 2008 6:33 am

    Tips 3 and 4 are really bad. It’s much better to use certain coding styles.

  12. 12
    Mike
    November 18th, 2008 6:33 am

    This is just blatant irresponsible use of the word “advanced”

    How the heck is knowing the difference between == and ===, advanced?
    or that str_replace is faster than regex?

    You learn this crap in your first pass through the manual.

    I eagerly clicked to read this article because i thought to myself, ‘ok, something new has been found out’ and all i found was this marketed garbage.

    shame on you.

  13. 13
    oelmekki
    November 18th, 2008 6:34 am

    I like this article, it points out a regular problem : performances vs legibility.

    Personally, I always drop the brackets when I can (meaning : a short test and a single short consequent). I know this is considered to be less readable, but if it is the case, it’s probably that this is the consequent (or the test) that isn’t readable enough, not the conditional form itself (providing you use a good indentation).

    On the other hand, #10 seems to be definitively tricky when you read it.

    @matt : I agree with you, but here, it is to use caching techniques *and* to write fast code. The audience must be extreme speed requirement applications.

  14. 14
    SSF
    November 18th, 2008 6:40 am

    You PHP people are funny

    1. If you don’t know the difference between comparison operators you shouldn’t be coding.

    2. Use brackets, please use them, they make the code easier to read and it’s good practice.

    3. If your code is open to SQL Injection then you don’t know how to code. I could understand people having this problem ten years ago.

    4. Shortcut else? Just lazy mans code.

    Tip of the day! Use ASP.NET/C#.NET

    C# is an ISO standard, I don’t think PHP is?

  15. 15
    Giovanni Battista Lenoci
    November 18th, 2008 6:47 am

    I don’t agree with tip 4, dropping brackets make code less readable.
    I use sometimes ternary operators, but also this tecnique make code less readable.
    I’ve never tested a code with brackets an without brackets, but I don’t think that the results are so different.

    Reguarding tip #9, I don’t know what was in the writer mind, but without an explanation this could lead to unwanted results:

    $a = 5;
    $b = $a;
    $a = 10;
    echo $a."-".$b; // 10 - 5
    $a = 5;
    $b =& $a;
    $a = 10;
    echo $a."-".$b; // 10 - 10

    For other tips, some are ok, some are banal.
    I suggest to change the article title in to 10 Advanced PHP Tips To Improve Your Programming (not so much)

  16. 16
    kidsinhalf
    November 18th, 2008 6:47 am

    troll ?

  17. 17
    wohoos
    November 18th, 2008 6:53 am

    Great but you should rename the post to:

    “6 adavanced tips to mess up your code!”

  18. 18
    Olivier
    November 18th, 2008 6:59 am

    Tip 4 is just bad advice, it goes against most “best practices”. What if you add one more line in the future? You’ll forget the brackets and your code doesn’t work as it should!

    Tip 9 is just as bad. It even goes against Zend recommendations. In the Zend recommendations it is explicitly stated that you should never assign by reference unless you really need it. Also the other side-effects this might cause is another reason to not use assign-by-reference just to avoid a suppression operator.

    Tip 6 is debatable. Some guidelines ask to not use ternary operators to improve readability. If I’m not mistaken that is one of the reasons it’s not in Python.

    The author of this article is one PHP Coder I’d rather not hire and it’s really a shame that this article has appeared on SmashingMagazine.

  19. 19
    Craig
    November 18th, 2008 7:01 am

    Agree with the previous posters, there are some dreadful tips here. Shorthand else and dropping braces do nothing but decrease the legibility of your code.

    Shorter code in terms of short cuts like these are not a sign of good code. “Anything that can be done to make the code simpler and smaller is usually a good practice” is a terrible generalisation. Far better practices to adhere to are following OO programming principles that encourage reusable, modular code.

    Furthermore, the article is contradictory – it encourages you to use a framework, but those frameworks have coding standards that automatically invalidate these two rules! For example, the Zend framework states: “PHP allows statements to be written without braces in some circumstances. This coding standard makes no differentiation- all “if”, “elseif” or “else” statements must use braces.”

    This article is a good idea, but has been poorly thought out.

  20. 20
    Gyorgy Fekete
    November 18th, 2008 7:05 am

    I don’t agree with the 4th tip.

  21. 21
    Targhan
    November 18th, 2008 7:05 am

    “Drop those Brackets” is a bad tip…

  22. 22
    Joshua M
    November 18th, 2008 7:08 am

    I’m with everyone else, even before I read the comments.

    That’s a list of things to do if you’re a lazy developer, for the most part.

    I like the logic behind Apple’s Objective-C standards. Write more, not less. Be more descriptive.

    We spend more time reading code than writing it for the most part, lean towards readability.

    #6 is iffy. Ternary operators have their place, but I’ve often seen them overused.

    #8 is even tricky. You shouldn’t use a framework unless you really understand the language. I use Zend, including the whole MVC pattern it supports, but for a new developer to use it is a bad idea. No framework is perfect. As much testing as gets done, there are always bugs. I’ve had to fix issued in Zend before, and more in Cake… not terrible, but for a new developer they are going to be lost and never understand what the problem is…

    Poor article, well below the standards of this site.

  23. 23
    C David Dent
    November 18th, 2008 7:10 am

    Actually thee difference between single-quote ‘ and double-quotes ” can add up over an entire application. For example, the command:
    $var = 'Test';
    $st = "This is a string called $var";

    vs.
    $st = 'This is a string called ' . $var;
    in the first line, the string will be parsed for variables and then they will be evaluated. In the second line the two strings are concatenated. The second can offer some speed advantages. Even if the first string did not contain a variable it would still be evaluated for variables.

    In cases where you use a string as an index (in an array for instance) you would find that
    $my_array['keyvalue'] would be more efficient than $my_array["keyvalue"]or (heaven forbid) $my_array[keyvalue].

    If you do a lot of string wrangling (in localization for instance) you will notice a difference in speed.

  24. 24
    Neilio
    November 18th, 2008 7:15 am

    #4 contradicts how he wrote #6 as he’s using brackets in the if() statement.

    I used to write code using no brackets for one-lined statements, but I look back now and think “WTF?”. It’s formatted nicely in #9, but in all fairness, you would probably miss that you are doing an if() statement there if you are just breezing through code; least when I breeze through now, I see where I did loops/if()s and such like as these are the most comment error places I find in my code.

    C David Dent: I also find using ‘This is ‘.$value makes it easier to spot where the variables are in a string and forcing you out of causing possible errors.

  25. 25
    Moritz Stefaner
    November 18th, 2008 7:17 am

    Sorry, but 3 and 4 are definitely bad advice. 6 has some nice applications, where it really looks better, but I wouldn’t overuse it either, especially with lengthy conditions and value assignments.

  26. 26
    zero0x
    November 18th, 2008 7:22 am

    yupii symfony ;)

  27. 27
    Jeremy Martin
    November 18th, 2008 7:24 am

    You should apply #6 to #3:

    $x = (this condition) ? 5 : 10;

    It only makes one assignment (unlike the “shortcut” version), and requires even less code. I realize people have mixed views on the ternary operator, but it’s honestly only confusing to people who refuse to use them.

  28. 28
    Paul
    November 18th, 2008 7:33 am

    i have to echo those concerns about 3 and 4 … particularly #4 with respect to code readability and future maintainability. i work with a relatively large php code base that was written back in the heyday of php 4 and among all of the fun procedural practices that i am cleaning up at the moment to convert to OO, i am very happy that the practice of leaving out braces was not used.

    good stuff otherwise! i can’t stress enough the importance of #7 … we have seen no less than a 400% increase in efficiency by utilizing memcached. the use of a framework is recommended as well. i personally recommend Zend Framework for anything other than a small rapid prototype (it has a flexible use at will architecture).

  29. 29
    Maarten
    November 18th, 2008 7:42 am

    Thanks. PHP tips are always welcome!

  30. 30
    MySchizoBuddy
    November 18th, 2008 7:54 am

    Wrap your string in single quotes (’) instead of double quotes (”) is faster because PHP searches for variables inside “…” and not in ‘…’, use this when you’re not using variables you need evaluating in your string.
    http://spindrop.us/2007/03/03/php-double-versus-single-quotes/

  31. 31
    hasse hansen
    November 18th, 2008 7:56 am

    Dropping the curly brackets, is very stupid, it makes the source less readable, and very easy to make mistakes, if you’re going to add a code line to that part of the sourcecode.
    So my tip would be, Use curly-brackets all over..

  32. 32
    aditia
    November 18th, 2008 7:58 am

    About using framework, beginner PHP developer could save time doing fast deadline project, but some of my friend are experienced in PHP, doesn’t like using framework, because they already have their own framework
    and better using bracket to make code more readeable, see coding standard from CakePHP

  33. 33
    Gordon
    November 18th, 2008 7:58 am

    Drop the brackets: All I can say to this one is, NO! As a young programmer I’d omit the brackets all the time if it was only 1 line. But then what happens if you discover later on you need to do more stuff based on your enclosing condition? Now you have to add the brackets back in. As code gets more nested the readability tends to go down and if you fail to enclose your 1 line statements in brackets the situation only gets worse. A much much better tip would be, “Always use brackets, even if they only enclose 1 line of code”.

    The else statement tip has issues too. The if – then – else form has the advantage that the variable only gets set once. In the no else case, the variable can be set twice if the if condition is met. If you have an expensive function where the variable set is instead then the no else approach can get very costly. It also reduces readability as the logic tree the programmer is implementing can be obfuscated. If you see an if … else in a piece of code it’s obvious that there’s a “fork in the road” at that point where one of two blocks of code will be executed. This isn’t so obvious in the no else case. The size of the PHP script has no bearing whatsoever on the size of the output and the longer versions are more readable, and the poor bastard who has to come along and maintain your code in a few months time might just be yourself. It’s amazing how much you can forget about your own code if it’s not crystal clear what it’s doing.

    As for the final tip, this one carries an important caveat. You’re using a function for a job other than the one it was intended for, so be sure to leave a comment in your code explaining this. And while it might be five times faster, the time difference is probably not going to be noticeable unless you’re processing massive amounts of data in a loop. Beware premature optimization.

    The biggest performance hit you’re going to take in most PHP applications is almost certainly going to be the cost of talking to your database. My advice here is to treat talking to the database as if you’re looting for supplies in a zombie move – Get in, grab only what you need and get the hell out. The more queries you perform the slower your application will be, the more data the database returns in response to a query the slower your application will be, and the general rule is you’ll be doing far more SELECTs than you will be doing UPDATEs, INSERTs or DELETEs. If data doesn’t change often then cache it and avoid the database query altogether.

  34. 34
    Glen Stansberry
    November 18th, 2008 8:17 am

    Hi Everyone,

    It looks like there was a bit of a fever about tips #3 and #4. While I might not have stated it in the article, their is a difference in the readability of the code vs. the speed of the code. If you’re concerned about readability of your code, then by all means skip #3 and #4. I was just trying to point out some tips that might fall under the radar of a typical article.

    Thanks for your comments and suggestions!

  35. 35
    Matthew Weier O'Phinney
    November 18th, 2008 8:18 am

    This post is full of inaccuracies and misleading advice. Here’s a breakdown of the more eggregious offences:

    4. Drop those Brackets
    First, they’re braces, not brackets. Brackets are used in array notation ([]), braces ({}) are used for blocks.

    This is actually a really, really bad idea when it comes to maintainability. Dropping braces makes it more difficult to read code, and to determine when the conditions stop and execution resumes. When you need to add extra statements, bugs can creep in if you forget to add the braces. There are good reasons why every sane coding standard requires that you use them.

    5. Favor str_replace() Over ereg_replace() and preg_replace()
    While I agree with this, the last sentence is misleading: “If you’re using regular expressions, than ereg_replace() and preg_replace() will be faster than str_replace().” str_replace() does not allow regular expressions, period. If you’re using regular expressions, you should use preg_replace(). (The various ereg functions are being aliased to preg functions starting in PHP 5.3.)

    9. Use the Suppression Operator Correctly
    The correct way to use error suppression is to not use error suppression, plain and simple. Unless you really, really know what you’re doing and have a good reason to use it, in most cases it will simply mask error conditions and make debugging harder.

    Furthermore, the examples shown are poor. Use the ternary: $albert = isset($albus) ? $albus : null; This is equivalent to the first example, which, other than lack of braces, is reasonable. The other two are poor; suppressing errors is bad, and the last example, assigning by reference, is almost certainly not what the user would desire (as updates to $albus would then update the value of $albert).

    10. Use isset instead of strlen
    This example is entirely misleading. isset() checks to see if the variable exists, plain and simple. Even if the value is null or an empty string, it will return true. If you are testing for the minimum length of a string, strlen() is the appropriate function to call.

  36. 36
    fird
    November 18th, 2008 8:28 am

    i get more tips reading the comment rather than reading the post.. and a big NO to “Drop the bracket”..

  37. 37
    Joshua M
    November 18th, 2008 8:34 am

    @aditia:

    Your friend would be better off adapting to a framework. I was the same way. I had my way of doing things for the longest time. My setup was surprisingly similar to Zend minus the MVC setup (which is optional).

    In the end, frameworks offer one thing that your own code doesn’t. Testing. Zend is tested through and through. Some immature components (generally in pre-release/preview versions) will have a few minor bugs… but once they get to a full release version, the bugs are generally gone. Zend is tested through unit tests, and through 1000’s of sites that employ it. Updates are frequent enough to stay current, and spaced enough to provide adequate testing time before full release.

    Like I said above, it should be the opposite (it never will be, people always look for the easiest path)… new developers should write their own code, experienced developers should use frameworks.

    By the way, a good case for ternary operation is zebra-striping tables.

    ex:
    $class = ($class == 'row_odd') ? 'row_even' : 'row_odd';

    If your classnames use numbers, you could easily use modulus to do it… but normally i don’t like using numbers in class names in my css

  38. 38
    Sam Dwyer
    November 18th, 2008 8:35 am

    Given that most people seem to have thrown in their 2c worth regarding most of the issues with this list, I thought I’d provide a quick link to the PHPtype comparison tables that people might find useful.

    How PHP deals with types and how functions such as empty() isset() and is_null() differ can be slightly confusing if you’re coming from some other languages.

  39. 39
    admin-of-the-web
    November 18th, 2008 8:35 am

    great article. :D love it. keep on smashing us

  40. 40
    Dave
    November 18th, 2008 8:44 am

    Shortcut the else? All you’ve done is add an additional assignment operation for your server to handle which may not have been necessary. This article isn’t so great.

  41. 41
    serans1
    November 18th, 2008 8:44 am

    nice article

  42. 42
    LC
    November 18th, 2008 8:50 am

    I try to learn Zend Framework for some time now but it’s quite difficult to start because it’s so modular and open. Even the Quickstart often get big changes ! For sure you can set up a project quickly but to understand the real basis of the MVC and all the modules is quite handy.

  43. 43
    Adam C
    November 18th, 2008 8:57 am

    I know very little PHP and want very much to start learning. Based on the comments it would seem that this article in general is feeding me bad advice. Not good for anyone trying to absorb knowledge. I often look to Smashing Magazine and the like to inspire and help my development skillset.

    Smashing, please don’t be responsible for the bad practises that would result from someone like me reading this type of post. I don’t want to start my PHP adventures off badly. It’s a good thing I always read the comments from the smarter people in the room!

    Thanks to all you responsible and insightful commenters for keeping us lesser humans out of danger. Keep fighting the good fight!!

  44. 44
    Jeremy Martin
    November 18th, 2008 9:06 am

    I’m feeling a little sympathy for Glen here, being trolled to death and all – but if SM is listening, this post isn’t helping your site much. In a nutshell, most of the tips aren”t “Advanced” as the title presumes, and the only tips that do tread in “advanced’ territory are misleading or flat out incorrect. Even the basic tips are naive at best, ignoring commonly accepted best practices and resulting in inefficient run time. I don’t want to throw out the baby with the bath water (and props to Glen for his contributions) – but this article should be pulled…

  45. 45
    Nico
    November 18th, 2008 9:22 am

    Whoa, no response from SM, yet? Amazing :|

  46. 46
    mentalic
    November 18th, 2008 9:26 am

    Using a well known framework can really help. You can invite other coders to ‘hope in’ your project and start developing with ease. As for the other tips all of them are sometimes bad/sometimes good.

  47. 47
    swyftdahoe
    November 18th, 2008 9:38 am

    Wow. Shortcut the else? lol Okay, that’s definitely not good advice. That’s an example of being too clever for your own good.

  48. 48
    Davin
    November 18th, 2008 9:41 am

    $x = (this condition) ? 5 : 10;

    Nesting ternaries is a bad idea, but after you learn them, they can make the code more readable if used for short blocks of code.

  49. 49
    mdrisser
    November 18th, 2008 9:54 am

    Forget Tip #4.

    That is one of my pet peeves. Never leave out the braces. While on the surface it seems to save time it actually creates further problems.

    First and foremost is readability. In 6, 8 12 months when you come back to your code you may very well spend an inordinate amount of time trying to figure out what you were trying to accomplish. Then there’s the case of someone else who may need to work on the code you created. They’re going to be wasting time as well.

    And finally as Matthew Weier O’Phinney pointed out, there’s the issue of bugs creeping into your code.

    Usually SM’s articles are great, but this one borders on the irresponsible.

  50. 50
    Adam K.
    November 18th, 2008 9:56 am

    I feel that some of these tips are a sure fire way to introduce bad habits to a new programmer.

    Especially when it comes to readability and legacy code. I really don’t think you shouldn’t use the curly brackets just to say a few lines of code. This isn’t even a standard practice – just standard laziness.

  51. 51
    Clemens Krack
    November 18th, 2008 9:57 am

    This is really a bunch of pretty wildly mixed tips.
    Tips like memcached or using a framework are certainly only useful for more experienced developers.
    Those however, would never drop common coding guidelines and readability to weird code that’s faster written or shorter as in lines.

    Ternaries are sometimes useful, however when having a quick glance at your own code, you’ll never really interprete them as fast or correct as a proper if/else statement. Same goes for the tip of avoiding the else at all.
    And never ever nest ternary operator statements.

    For unexperienced programmers writing smaller applications, it’s definitely overthrown to use a framework or to consider using memcached aswell.

    I’d say those tips should be regarded critically and i’d love to see a followup correcting that.

  52. 52
    Ryan
    November 18th, 2008 9:58 am

    this hurts my head. Don’t drop the braces.

    single quotes are not faster than double quotes. If you say they are… then show the proof. I’ve run test after test of several servers and even at 10,000+ iterations the differences are negligible. Maybe in PHP 3 running on a Pentium 1 with 128MB RAM they were faster.. but come on people.. quit reading 3 year old blog posts and parroting them as truth.

    Also, it’s interesting how one tip such as “dropping braces” is included for speed, but the example of using Cake PHP framework is given when IMHO it’s an everused bloated piece of junk. Frameworks have their place and I’m not saying they aren;t good.. I just fail to see the consistency among the tips.

    One good one was the memcache tip. That is something that can help developers speed things up when they are trying to build an ap. but it doesn’t really help your programming.

  53. 53
    Adam
    November 18th, 2008 10:07 am

    As both a web developer and a desktop software engineer, I’m really surprised that this article made it through the doors of Smashing. None of this is advanced by any stretch of the word. Some of these tips are for beginners (such as learning operators for a language) and some of these tips are just plain inaccurate or bad.

    Unfortunately, the creed of minimizing file size on the web to promote fast load times has forced itself upon the development community, leading us to believe that if we remove brackets and else statements, we will somehow see a performance increase in our web applications. For example, tips 3 and 4 have NO affect on performance because if statements inherently add on constant-time performance (unless nested with for loops or while loops). Actually, 4 might have a DETRIMENTAL affect on performance because you are assigning a variable at most twice, whereas with if/else statements you assign a variable at most once, but regardless is a NEGLIGIBLE and irrelevant factor that cannot be associated with performance.

    Also, if any of you have ever written in C/C++ before, you would know that tip #9 needs WAY more of an explanation of the consequences of using references. Are PHP references like C references? Not totally, because PHP references do not access the same address space. Nonetheless, they borrow the idea of pointing two variables to the same object content. =, replaces the ‘destination’s value; =&, changes the destination. So in a true computer science definition, references aren’t really referencing anything, and you are wise to avoid them at all costs.

    And I complete agree with Matt Weier on #10 – two functions used for two totally different purposes.

    This is disappointing.

  54. 54
    Md Emran Hasan
    November 18th, 2008 10:10 am

    This is the first time i’ve been disappointed by a SM post :( The “tips” mentioned here are more like cheeky shortcuts, let alone being advanced. While some of them might help a new developer save a few mins or so, but will result in non-readable, non-maintainable coding behavior to be regretted later.

    Apart from the tips point of view, I’d suggest newly joined PHP devs to have a look on Zend Framework’s excellent coding standards if you’d like to build a coding style that majority of the PHP developers out there adhere and understand.

    The comments here already have a number of excellent tips, so you might follow some of them instead ;)

    @Glen: no hard feelings, but you should have thought twice before deciding on the title of the post.

  55. 55
    Öde
    November 18th, 2008 10:16 am

    Laaangweilig!

  56. 56
    kevin
    November 18th, 2008 10:20 am

    REPLY TO COMMENT 14 (SSF (November 18th, 2008, 6:40 am)

    I also don’t agree all tips in this post . Some of the tips I couldn’t follow. But these are just the tips for the some persons who have few or little knowledge about php programming from authors’ point of view. It doesn’t mean PHP guys don’t know about comparison operators. Did author said like that? Many junior guys don’t know difference between === and ==. Same thing like double quotes and single quotes difference.

    PHP is very powerful language, much more powerful than your stupid microsoft platform. Do some research on it.

    The point is whatever language you are using, it depends on you and you only. If you are a bad programmer, your work done will be bad. You can use any language you like. We got many options.

    Tip of the day just for you, just try to be the best in your field.

  57. 57
    Andre
    November 18th, 2008 10:23 am

    As people said, these are not “advanced” tips. But I think they work for smashingmagazine because it’s primarily a design blog, so a lot of the people coming here are not seasoned programmers, maybe involved on the light side.

    Also as people commented, don’t drop brackets to make the code smaller or a one liner. Better to just minify code on a production server and leave development code easy to understand and more inline with other languages.

  58. 58
    Timothy
    November 18th, 2008 10:30 am

    The suppression operator part was great! Thanks for the info, I always love to read new techniques in coding.

  59. 59
    Jehzeel Laurente
    November 18th, 2008 10:38 am

    I agree with Joshua M. This website smashes people with web design stuff :D But it sucks in programming stuff.. hehe :)

    but anyway, tips are just tips, so let’s just read the tips if we want, follow the tips if we want, and apply that tips if we want. If we don’t want, then it’s up to us :)

  60. 60
    Advanced programmer
    November 18th, 2008 10:47 am

    Yay, Im an advanded programmer now!

  61. 61
    Fabien
    November 18th, 2008 10:55 am

    @ kevin: “PHP is very powerful language, much more powerful than your stupid microsoft p
    platform. Do some research on it.”

    not sure what you mean with “power”, if it’s performance .NET wins by far, if it’s a proper language, then microsofts C# is probably the most respected language nowadays, if it’s about libraries and community, then C#/.Net have some of the most experienced programmers (and nearly no kiddies).

    so, please explain me what you mean with PHP’s “power”.

    @ kevin: “The point is whatever language you are using, it depends on you and you only. If you are a bad programmer, your work done will be bad. You can use any language you like. We got many options.”

    haha, no. this is only the case with php. any other serious language does not allow you to code so much crap (at least with such a freedom). you ever tried any “real” language (Java, C#, ada, eiffel, pascal)? i don’t think so, because you would know it better.

    that “it’s all in the programmers hands” is stupid and a specific PHP and assembler (!) topic, it has nothing to do with state of the art programming. there’s a reason why PHP has so may frameworks – the fundament highly encourages bad coding style (well, it nearly forces people to write bad code).

  62. 62
    Martin
    November 18th, 2008 11:03 am

    Kind of obvious, really. #10 can be useful in some cases, but it’s usually not really something that’s performance-critical.

    And no, except for memcached, none of this is really advanced.

  63. 63
    Fernando
    November 18th, 2008 11:09 am

    mmm, i don’t think so, not too usefull.
    I’m working on a Web design company, and every time a have to checked somebody else’s work and he “drops the braces” i want to punch him in his face.

    I think all this “tip” were made for the very same guy who creates the sprintf() instance. Not usefull, very not readable & complicated.

    I’ll give you a very nice tip, do your work as commented and long as you can, don’t mess with the braces or the elses or anithing else, you will be thankful later.

    PD: other tip, if you’re novice on php and you wants to ease you work, don’t waste you time on this kind of articles, it will confuse you more. http://www.php.net will help you more!

  64. 64
    kevin
    November 18th, 2008 11:10 am

    @Fabien,
    “haha, no. this is only the case with php. any other serious language does not allow you to code so much crap (at least with such a freedom). you ever tried any “real” language (Java, C#, ada, eiffel, pascal)? i don’t think so, because you would know it better. ”

    Surprise you don’t agree with that, and you said “this is the only the case with php”. So, you are saying all .net programmers are doing good coding and we have to put PHP away? PHP is that bad??? Immm, where did u learn that? I started programming with Fortran 77, pascal, c, c++ and also visual basic, and then started web programming with coldfusion and classic asp, visual basic.net and then PHP. So, hope it answers your concerns. Go back to school man, funny guy!

  65. 65
    Lars Pohlmann
    November 18th, 2008 11:22 am

    Actually I think that the ternary operator “can” be useful at times, but you really have to be careful when to use it.

    And for “dropping the braces”… this is a big NO. I have to maintain some code right now by somebody who did this all the time. It’s a horror to read…

    My tip: Use braces all the time, with proper indentation. If you have too many levels of braces, use new methods (with intuitive names) to capsule the code. Keep the structure of the code always in a way, that you can understand the meaning behind it with a short glance.

  66. 66
    Joshua M
    November 18th, 2008 11:26 am

    @Fabien:

    Really? PHP is the only language that lets you use bad habits, huh? .Net, specifically C# allows the same things. Skipped brackets, overuse of ternary operation, etc etc… Bad habits exist in all languages. Aside from python, which forces tabbing, most languages do nothing to force style.

    I work in PHP, C# and Objective C. Obj-C is the best of those when it comes to style. Not because the language itself requires any style, but because the API/Framework behind it (and cocoa) force you to use a style.

    It cracks me up to see the things supposed “real” programmers say about PHP or other scripted languages. .Net is JIT Compiled, the same as PHP… get that? You’re as much a script kiddy as the rest of us… they just put an intermediate language between code and runtime.

  67. 67
    Vance
    November 18th, 2008 11:28 am

    This is horrible advice… seriously. Dropping brackets severely reduces legibility and leads to other problems for novice coders like not knowing that when the brackets aren’t there, only the next single line of code will be based on the conditional statement. How did this article get published?

    With PHP5, you should almost never use the assignment operator, and absolutely SHOULD NEVER use it to avoid errors!

    2 ACTUAL tips to better code:
    1) Code to the Zend Coding Standards
    2) Turn ON error_reporting to E_ALL | E_STRICT

    This article is extremely misleading…

  68. 68
    Joshua M
    November 18th, 2008 11:29 am

    Also, to the article itself. I found it amusing that you used as examples code with both brace styles…

    ex:

    if(1) {
    // something
    }

    and

    if(1)
    {
    // something
    }

    Not that I preach either one. I prefer the former, but if a coding standard exists in your workplace, you follow that of course. I just thought it was funny to see examples in both…

  69. 69
    Raam Dev
    November 18th, 2008 11:36 am

    Since these “Advanced” tips appear to be aimed towards newbie PHP programmers, I thought I’d mention another useful tip:

    $mynum = $mynum + $num;

    is equivalent to

    $mynum += $num;

    But my best advice to any newbie PHP programmer is this: look at and read lots and lots of open-source PHP code written by professional PHP developers. If you don’t understand something, read the manual on php.net (use the search box to find functions) and try to understand why things are done the way they are.

    There are dozens and dozens of good open-source PHP projects that you can learn from (WordPress, Gallery 2, etc).

  70. 70
    Lars Pohlmann
    November 18th, 2008 11:37 am

    @all the php-bashers and php-defenders: come on guys. i really like php, you can write fine code with it if you’re disciplined, but it’s also clear that you can write some very messy code in php (and many people do). i wouldn’t say it’s mainly the fault of php, but this problem *does* exist. period.

  71. 71
    TravisO
    November 18th, 2008 11:43 am

    Half of the advice in this article is garbage, not because I don’t agree with it, but simply because the fact this article is suppose to be about “improve your programming” and half of the points here are purely cosmetic/style choices.

    Dropping brackets, ternary and shortcutting if/else doesn’t “improve” code, it’s purely a personnal choice but I’m not a fan of any of these because readibility is more important than reducing the number of lines. None of these changes will affect the speed or memory usage of your application. Too many coders already produce unreadable code, anything that makes code more illegible is a bad thing.

    This whole article reeks of some poor concept that less lines of code is absolutely better. While less code means less testing, using the frameworks were a great idea,

    Ultimately, this article doesn’t satisfy what the title lays it out to be about, this is more of a “the way the author codes”, this could have been a much better article.

  72. 72
    kevin
    November 18th, 2008 11:59 am

    @Fabien:

    Usually, people coming from designer background, they like .net as they could create applications with drag and drop. They don’t even know what is happening in background of those generated codes.
    They are scared of hand coding, so they wouldn’t want to use scripting languages like php, perl etc.
    I am not talking about experienced .Net programmers, just talking about some beginner/designer people. Don’t take it personally. :D

    Anyway, we can use whatever we want, but just don’t insult php community like comment#14.
    This talk should stop now.

  73. 73
    sean
    November 18th, 2008 12:27 pm

    Article blows. This is not useful for advanced users. This is not even useful to intermediate users because the advice is bad. For example: don’t get rid of brackets– most programming standards mandate brackets.

  74. 74
    David
    November 18th, 2008 12:40 pm

    Some excellent tips, some dumb ones. And some completely contradictory ones too.

    Like use a framework (an excellent tip), particularly CakePHP (one of the best). The CakePHP coding standard specifically advises against using ternary operators and not using brackets around code blocks in control structures.

    Making your code more efficient is a laudable aim. Making it harder to read and maintain is certainly not.

  75. 75
    xenon
    November 18th, 2008 1:31 pm

    “Tip of the day! Use ASP.NET/C#.NET” – lol, not really a solution is it?

    Yeah not all of these tips are brilliant but most of them are useful for beginners. One of the best things you can do to improve your code is to download one of the frameworks and study them. Also look in to design patterns for improving code and making maintenance easier.

    Also, I recommend commenting your code. Sounds obvious but when you are working on code that makes sense at the time, when you come back to it the reason for the code may not be immediately obvious. Save yourself and fellow developers time by commenting, you’ll be grateful you did!

  76. 76
    Mats Lindh
    November 18th, 2008 1:32 pm

    An almost complete failure of an article, which contains advice that you should avoid implementing.

    #1: A general rule for any web developer. Keep this in check. If you’re doing it properly, use prepared statements and a library that supports them. The cheat sheet does not contain any advice for PHP programmerings in particular.

    #4: Keep the braces. It will enhance readability and avoid bugs from creeping in from inproper indenting.

    #6: Use ternary operators if it actually makes sense and increases readability. Very often it does not. If you can’t tell the difference, don’t.

    #9: Do not use the suppression operator. If you have to use the suppression operator, you’re most likely doing something wrong. There are a few cases where it has it’s place, this is not it. If you have a variable that may not exist, then don’t assume that it does.

    #10: Don’t. It will not work properly with UTF-8 strings, and PHP6 will use UTF internally. Doing something like this might require a rewrite in the future, and using isset() to test for string length will be very confusing for developers not familiar with your code.

    Readability and easy understandability are much more important than squeezing out one or two nanoseconds. If you’re calling strlen() in a loop and are afraid of the performance hit, just store the result in a variable instead.

    Do not micro optimize.

  77. 77
    ashorlivs
    November 18th, 2008 1:35 pm

    TIP #11: DON’T GIVE CODING TIPS WHEN YOU’RE A GRAPHIC PRO.
    All caps yeah.

  78. 78
    geekamongus
    November 18th, 2008 1:37 pm

    I always wondered what the @ sign was for…doing Google searches on it would always fail, for some reason. Thanks!

  79. 79
    Gene
    November 18th, 2008 1:41 pm

    good article, thanks!

  80. 80
    LC
    November 18th, 2008 1:47 pm

    Tip of the day! Use ASP.NET/C#.NET
    C# is great and Asp.net may be a good choice for internal web apps, but I tend to think it takes the fun out of web developement and is a mess for public websites. Maybe the MVC + jQuery will change that.

  81. 81
    Schmoo
    November 18th, 2008 2:00 pm

    To be blunt, some of this advice is bad and still more is trivial. However, the vast majority of the comments here appear to be from those whose coding ability comes at the expense of all traces of social skill, namely civility… and people wonder why programmers have a reputation of being awkward, girlfrend-less shut-ins?

  82. 82
    cbagov
    November 18th, 2008 2:11 pm

    Are they advanced ? Naaah..
    It’s just any programmer should know.

  83. 83
    Vitaly Friedman & Sven Lennartz
    November 18th, 2008 2:15 pm

    @all: thank you for the constuctive criticism, guys. We appreciate your feedback in the comments and we hope that both newbies and advanced developers can learn something from this page. Thank you.

  84. 84
    danilo di moia
    November 18th, 2008 2:16 pm

    Code in example 6 is not correct (and yes it is not correct also in referer page…).
    It should be:

    $action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

    // The above is identical to this if/else statement
    if (empty($_POST['action'])) {
    $action = 'default';
    } else {
    $action = $_POST['action'];
    }

    Look at http://php.net/operators.comparison

  85. 85
    Chris
    November 18th, 2008 2:31 pm

    I find code readability and long term maintenance is enhanced by using brackets and avoiding ternary operators. Just my opinion. For one line assignments, I like the tip on avoiding else statements. Nice. Anything more than a one line assignment and I would keep the else statement for maintenance and readability.

  86. 86
    Eddy
    November 18th, 2008 2:45 pm

    I agree with Chris, don’t drop brackets on multiple instances. You will be happier when you read your code after a few months.

  87. 87
    jim
    November 18th, 2008 2:46 pm

    Tip #4 looks like something out of the Daily WTF. Avoid being cute and clever at all costs.
    JIm, ColdFusion Developer.

  88. 88
    jony
    November 18th, 2008 2:51 pm

    I’m not a Pro in PHP, but “Shortcut the else” is really somehow stupid…

    If someone is going to read your code (and you have to assume that someone will do it if your code is important), he will not understand why on earth you first assigned the value to than do the real check.

    You are just messing up your code in favor of nothing!

  89. 89
    tylerv
    November 18th, 2008 2:56 pm

    duh. noob article.

    turd cassarole.

    frameworks slow down small site development by the way.

  90. 90
    awalsadja
    November 18th, 2008 3:02 pm

    smashingmagazine helps me a lot.
    especially on this kind of article..
    thanks, salute to you..

  91. 91
    Andrew
    November 18th, 2008 3:07 pm

    Tip #3 is really bad advice in terms of readability. If you want to do something when a condition is false use the ELSE statement, not a completely disconnected expression outside the if/else

  92. 92
    Ace Web Design
    November 18th, 2008 4:24 pm

    Great article thank you very much for sharing. Some of these are certainly overlooked at times

  93. 93
    fred
    November 18th, 2008 5:50 pm

    Advising dropping the braces on a one-line block (in pursuit of “quicker, leaner code”) is about equivalent to advising the use of very short variable names. That is, it’s equally stupid.

  94. 94
    JSHAW
    November 18th, 2008 6:13 pm

    great list, super helpful for those days when your brain just doesn’t work. helpful reminder

  95. 95
    John McClumpha
    November 18th, 2008 6:18 pm

    in reference to using the ternary operator – I have to agree to an extent with the comments stating it makes debugging/reworking code more difficult… but I feel there’s a bigger issue at stake which is speed

    A benchtest I ran a little while back shows the speed comparison between the ternary operator and longhand if/else statement – ok I admit it’s only a 2.78% speed decrease for the ternary operator – but shows that shorter code doesn’t always equal better speed.

  96. 96
    Ben
    November 18th, 2008 8:52 pm

    Nice article, however I don’t agree with the “drop the bracket” mentality at all. It helps making the code more readable by sectioning it properly and in most editors it also gives you the chance to highlight codeblocks (between curly brackets) via shortcuts which again helps coding.

    Dropping 2 characters just to write:

    if ($gollum == ‘halfling’) $height –;

    instead of

    if ($gollum == ‘halfling’) { $height –; }

    is pointless and not neat in my opinion. If you want to ’save’ space with your if-then-elses use the ternary operators.

    just my 2cents

  97. 97
    jacobr
    November 18th, 2008 9:38 pm

    Article title is misleading. Some of these tips are reserved for entry level programmers. I strongly feel that programming articles like these be okayed by someone who actually knows his stuff before publishing on the web.

  98. 98
    Mohd Amjed
    November 18th, 2008 10:02 pm

    While everything seems great, am a little reluctant about the idea of dropping the brackets …i think it actually leaves the code diffcult to understand, especially when u have multiple conditions to test using the short circuit operators ..

  99. 99
    Brijesh Bolar
    November 18th, 2008 10:18 pm

    I liked this article. I hardly work on php coz m a flex developer, but after reading this article and its comments I could borrow a lot of guidelines and points that could be helpful to programmers in general.

    I agree with comments on paranthesis and braces. Its a good practice to have them. It makes the code readable and also there is always a possibility of adding more code inside your conditions.

    There is one more point I can add to this list. While using loops its better not to use expressions inside the loop condition, the value for which is going to remain constant throughout the loop.

    for example:

    while(i < names_array.length) {}

    is same as

    var namesArrLen = names_array.length;
    while(i < namesArrLen ) {}

    but more optimized.

  100. 100
    Akiva Levy
    November 18th, 2008 10:40 pm

    I may be lambasted for this, but in my opinion, choosing a bloated framework like CakePHP would not really improve your programming skills–especially when you consider it’s fetish for PHP 4 focused code. Why not choose a more modern framework that implements only PHP 5 style OOP? Besides, PHP 4 will be dead in the water soon, so how is that really helping anyone?

    That said, if you don’t have the time to write your own SQL injections, there is a great SQL injection plugin for Firefox that can automate it for you. Yum!

    Akiva Levy, founder of Six Thirteen Design
    http://sixthirteendesign.com

  101. 101
    sandeep
    November 18th, 2008 11:10 pm

    Nice Article…. Thanks You!

  102. 102
    Adam Jorgensen
    November 19th, 2008 12:20 am

    Most of this stuff is real no-brainer shit. Stricly for the n00b of mind…

  103. 103
    Blaise Kal
    November 19th, 2008 12:56 am

    Advanced tips? I’m sorry, but if you have trouble understanding SQL injection, comparison operators or the difference between str_replace and ereg_replace, you’re an amateur. You shouldn’t read this article. Instead, read a professional tutorial where good practises are explained.

    Also, the tips are a random collection of bad practises, I-already-knew-that’s and who-the-beep-is-doing-that-anyway’s.

    Thanks for the efforts, Glen, but next time you’re writing an article, please know what you’re talking about.

  104. 104
    xman
    November 19th, 2008 1:44 am

    Some truly awful advice here. (but I am a fan of the ternary operator which actually improves readability when used appropriately). Most of the advice is retrogressive rather than advanced!

  105. 105
    Yunus T.
    November 19th, 2008 1:54 am

    Great as usual, but in 1. item name is Ferruh Mavituna…

  106. 106
    Jonesy
    November 19th, 2008 2:09 am

    “Switch to .Net and do it properly” would be a good tip.

  107. 107
    Ghol
    November 19th, 2008 2:19 am

    @Jonesy: You appear to be confusing your boolean operators.

  108. 108
    David Grudl
    November 19th, 2008 2:31 am

    One half of tips are nonsense or ways to hell. Please do not trust author, read rather some coding standards.

  109. 109
    Lewis
    November 19th, 2008 2:52 am

    Losing brackets makes it hard to read, but alternative syntax does exist for control structures.
    Namely replacing the opening bracket with a colon then utilising the ‘endif’:

    if ($a == 5):
    echo "A is equal to 5";
    endif;

    This does help punctuate control structures where a closing bracket can occasionally be confusing. Works with for, while, ifelse etc.
    That said I use brackets, and I find the ternary operator useful in some instances.

  110. 110
    Martin Joergensen
    November 19th, 2008 4:34 am

    All u crly brckt fans. Get a life. Rdblity mns notn ths dayz! U wrt a=a+1; print a; or print ++a;?
    Bst prctises, my a++ ;-)

    And SSF, you .net people are funny. C# may be ISO, ANSI, politically correct, sharp, grown up or whatever, but how come most of us (and many of you) use PHP anyway? Stupidity? Ignorance? Productivity?

    Martin

  111. 111
    Martin
    November 19th, 2008 4:58 am

    for the 3rd tip I’d use this ;)
    $x = (condition)?5:10;

  112. 112
    Todd
    November 19th, 2008 5:32 am

    Tip #6 is wrong!! It’s not set to $todo but to $action.
    It should be:

    //PHP COde Example usage for: Ternary Operator
    $action = (empty($_POST[’todo’])) ? ‘default’ : $_POST[’todo’];

    // The above is identical to this if/else statement
    if (empty($_POST[’todo’])) {
    $action = ‘default’;
    } else {
    $action = $_POST[’todo’];
    }
    ?>

  113. 113
    Chris
    November 19th, 2008 7:38 am

    #3, #4, #6 and #9 are all bad techniques. And will not save any noticeable time when running the app at all.

    Your actually teaching the new kids the bad habits of the old dogs. Code should be readable, if you want to teach a great technique teach the importance of proper commenting in your code and the importance of consistency.

    This article really let me down.

  114. 114
    Jon
    November 19th, 2008 7:41 am

    I agree with previous posters. Easily readable and maintainable code is most important. Can’t maintain it if it’s difficult to read.

  115. 115
    Matt
    November 19th, 2008 9:06 am

    I just recently found SMM, but in the short time I have been going through the articles, almost all of them have contained invaluable information except this one. If you are a new programmer, please ignore this article and read the comments. I make my living fixing botched programming jobs, but nothing is worse than someone who has only a rough grasp of how to program, trying to streamline their code. If you don’t know what refactoring is please do not write an article on how to optimize your code. None of these tips will help in any significant way. Cache your code and if you are still not seeing enough performance, hire someone to help.

  116. 116
    Zachary
    November 19th, 2008 9:45 am

    This article is ridiculous. Using the word ‘advanced’ for this article is absurd and you should feel like a fool for writing it. These are tips for lazy, messy coders and no one should heed this advice. Other than the bit about SQL injection all of the above tips should be avoided if you consider yourself even half of a programmer. I wouldn’t want to take over a project you were working on. I can’t stand having to track down brackets and braces that aren’t there. Readable code is far more useful than shortened code. Most of these tips don’t even achieve any significant performance gains. I’ll stick with proper coding techniques and leave the lazy stuff to lazy people.

  117. 117
    neptune
    November 19th, 2008 10:09 am

    DONT USE A FRAMEWORK… most of them have too much overhead.

    Believe it or not MOST of the time you get things done faster because you know YOUR OWN code over others and its a waste of time learning someone’s code (large code might I add)…just time consuming.

    Try your best to stay away from frameworks.

  118. 118
    Lars Pohlmann
    November 19th, 2008 11:25 am

    @neptune: I worked with symfony quite a bit, and i have to say: i disagree. framworks are boosting productivity once you got to know them. another advantage is that they force you to keep a certain structure. that might be annoying if you work alone, but it’s so much easier to bring additional developers into the project who already know the framework. they don’t have to learn *your* style of doing things, they just have to know the *insert name of framework here* style of doing things.

  119. 119
    David Perel
    November 19th, 2008 12:36 pm

    Lol, we still use Coldfusion but I think we will still take a lot away from what has been mentioned here.

    Great post, dugg.

    From the Couch

  120. 120
    peter
    November 19th, 2008 3:10 pm

    Lose #8 and it wouldn’t be a bad list. Less code to write sure is a time-saver, until the client wants something that the system was never built to do. Then you’re going to bleed money like a stuck pig. If you want it built right, build it yourself. Besides which, the dumbest know-nothing s.o.b. php people I know all swear by frameworks. Why? Because they couldn’t implement what it’s doing themselves with a gun to their head. Knowledge = power in programming. It’s the difference between a script kiddie and someone with a badge.

    Ternary operators, shortcutting brackets, and several others are extremely helpful if used intellegently. memcache is all about price/earnings. If your website isn’t trafficed enough to see real benefits then it’s not worth the time to implement.

    Honestly though, I really don’t see how this list is helpful to people at an entry level in the language except for the Operators list. If you don’t know that, then how are going to be getting into something like memcache? Most of those people barely understand how loop structures work. Put in more useful items like how to foreach() through a mysql return set intelligently and you’ll be getting somewhere.

  121. 121
    g0ma
    November 19th, 2008 11:42 pm

    This article should read x Comment Tips to Improve This Article

    LOL.

    I love the braces! Don’t wanna lose them.

  122. 122
    pbijl
    November 20th, 2008 1:31 am

    every tip has bad practise and bad advise attached to it.

  123. 123
    Ivan
    November 20th, 2008 1:40 am

    Why are so many “developers” here afraid of frameworks?

  124. 124
    foobar
    November 20th, 2008 4:44 am

    “Know the Difference Between Comparison Operators” ?? – seriously? – if you don’t already. what ARE you doing programming? – go back to flipping burgers

  125. 125
    Johan de Jong
    November 20th, 2008 5:26 am

    @123 Ivan:
    As a developer I do use a framework, but I wrote my own (which most developers have done). It’s not that the existing frameworks are bad or can’t do what I want, but when you need a very simple script or need something that isn’t in the framework you need to hack around it to make it work properly… which means more coding and even more debugging.

    I also note a lot of comments about tip 3, 4, 5 and 6; I use this way of writing for 2 reasons:
    1) it’s easier to write, which means faster coding
    2) it’s shorter in code, which means faster code (not with one execution, but think in millions)

  126. 126
    Riki
    November 20th, 2008 6:59 am

    As somebody said “Drop those Brackets” makes your code less readable.
    How many milisecs of coding takes you pushing 3 keys???? Please man…

  127. 127
    B.Droehnt
    November 20th, 2008 12:05 pm

    At last! With these tips at my fingertips I feel like I can handle anything.
    Seriously, the only thing that is more useless than these 10 tips is me commenting them.

  128. 128
    Matt
    November 20th, 2008 3:51 pm

    Man. People are tearing this up. I thought it was an excellent article. Thanks!

  129. 129
    Jeff
    November 20th, 2008 11:09 pm

    Yup, great article. Especially #1… Thank you.

  130. 130
    deepak panwar
    November 21st, 2008 4:43 am

    very good reply

  131. 131
    Jon
    November 21st, 2008 8:54 am

    Oh dear. I’m basically repeating what everyone else has already said, but a good half of these tips are really really terrible practises. First year CS courses should beat this kind-of behaviour out of people. I guess PHP programmers don’t do CS courses anymore :(

  132. 132
    fraggle
    November 21st, 2008 10:50 am

    Worst. Top 10 programming tips list. Ever.

    If you want a good programming tip, here’s one: don’t do “clever” programming tricks (like #3, #4, #6, #9, #10 in this article) even if it makes the program run a bit faster. It’s better to be clean, clear and maintainable. Use of the ternary operator should be a hanging offence.

  133. 133
    Rufus
    November 21st, 2008 1:52 pm

    I expected some.. well.. advanced stuff. This seems still basic to me, but anyway…

    I do not agree with tip #4. As much as I despise brackets, applying tip 4 to your code makes it less readable and more error prone. Sticking to a Coding Convention like Zend’s or Pear’s is a much better advice, if the only aim is improving code readability.

    Since you mention the Ternary Operator in #6 and claim improvement in code and performance. The Ternary operator is slower than the equivalent if/else statement. But I agree it can improve code readability if not used for lengthy code blocks, which would reduce readability.

    As for #8 “A Framework does help eliminate some of the overhead in developing Web applications and Web services.”: Well, I think the decision to use a framework should depend on the task at hand. They might just as well add much more overhead than they eliminate. And I can’t believe you advocate frameworks and dont even mention Pear.

  134. 134
    Mark A Hershberger
    November 21st, 2008 6:44 pm

    Also, LiveJournal is written in Perl (and the codebase is open source http://www.livejournal.com/code/), not PHP.

  135. 135
    Sai Gudigundla
    November 21st, 2008 9:56 pm

    Nice article. Thanks for the tips….

  136. 136
    Matt
    November 22nd, 2008 7:59 am

    For readability, I’d keep the brackets; they serve a valid purpose.

    Re. frameworks, I agree with one of the above comments; frameworks indeed slow down small site development, and are bloated. However, for enterprise level work involving many programmers, I can see a use. To increase one’s learning of PHP, I’m happy not to learn a framework, but rather concentrate on the language itself. It’s good to understand what’s going on in the black box.

    Thanks Smashing.

    Matt

  137. 137
    Stu The Rat
    November 22nd, 2008 10:10 am

    Oh Gawd!!!! Now I’m the first to admit that I’m a total & utter php virgin (Apart from a little bit of fiddling, successfully I might add, with some WordPress code) this article is such a TURNOFF it’s like trying to read a mongolian lawnmower manual. Jeez, it’s nurdtastic guff like this that KILLS any inspiration stone cold dead in it’s tracks. “Code is poetry?” Don’t make me laugh, it’s a right royal pain in the butt. Yeah php apps tend to be way cooler & superior in functionality, certainly in relation to the all that sad asp b0770cks, but give me Photoshop, a slice tool and the resulting simple html anyday. Death to the nurds I say DEATH TO THE NURDS!!!!

  138. 138
    Randy
    November 22nd, 2008 10:45 am

    Very useful info especially the SQL injection cheat sheet. Cool!

  139. 139
    David
    November 23rd, 2008 9:10 am

    ColdFusion is still #1 in my book. And there are free versions of the CFML engine now available.

  140. 140
    Joris
    November 24th, 2008 4:50 am

    Good entry :-)

  141. 141
    lookouts
    November 24th, 2008 8:20 am

    Useless. It does nothing for home country.

  142. 142
    Mindilator
    November 25th, 2008 2:23 pm

    1. Don’t stop with SQL injections, what about cross-site scripting attacks? Learn security, don’t just keep a cheat sheet.

    2. I agree with the others above, if you don’t know this you are not ready for advanced tips and tricks.

    3. This is just common sense. To program well you must think logically. This is how Microsoft wrote fifty miles of spaghetti code. Keep it clean.

    4. NO! If/else statements are not written in stone, and can easily turn into if/elseif/else statements. Omitting the brackets does a disservice to anyone maintaining your code including you. Btw, too many elseifs means use a switch instead.

    5. This is actually good to know. Learn up on all the string functions and their caveats (e.g. strpos returns 0 when matching the first position of the string, don’t mistake this for false).

    6. Ternary statements are just fine. The guy who thinks they’re a hanging offense is a jackass. If you can’t tell that the left side of the colon is true and the right side is false, you are also not ready for advanced tips and tricks. The trick here is to only use them for yes/no conditions, not something that break out into a series of elseifs, hence why you shouldn’t nest them.

    7-8. Good tips. The listed frameworks are good and subject to your own preference, but writing your own is just as good too, so long as you know that it’s solid. The advantage to public frameworks is that they’re supported by the community. You can’t think of everything. No… you can’t.

    9. This example doesn’t even apply the suppressor where it’s appropriate. Use it to suppress errors that aren’t worth catching with exceptions, like importing static XML into a SimpleXML object. Unless you think that’s not a waste of your time. Use try/catch blocks and the Exception class to handle errors, don’t just suppress them. And for the love of all that’s holy, set your error_reporting to 0 on production code.

    10. Even better than isset is empty. It checks against empty strings, 0, false and null values. Isset will throw an error on array indexes that don’t exist. You may not see them depending on your error_reporting value, but it’s just solid practice.

    My own number 11: Get certified. If you’re going to code a language that is as willing to let you hang yourself as PHP, f’ing learn it right. Don’t waste your and your client’s time without at least knowing the things required to pass the test. We wouldn’t need to correct articles like this if more people bothered to know what they’re doing.

  143. 143
    Alex Samsonas
    November 27th, 2008 5:35 am

    nice tips

  144. 144
    phpfanat
    November 28th, 2008 12:40 am

    Top 10 stupidest tips ever.
    #1 shows thousands of injections but no single word saying you are SAFE if just follow simple syntax rules for data and simple precautions for control structures.
    #4 is weird and even weirdest behind link.
    #10 is same stupid “optimisation” as #4. There is no real gain from these tricks. Its a trash to stuff programmer’s head.
    #2, #4, #6 are matter of style. Choose your own which suits you. that’s all. It’s just style, like color of your car. It affects nothing important such as power, speed, gas consumption. It shouldn’t show up under “improve your programming”.

  145. 145
    Dan
    November 29th, 2008 7:50 pm

    to be fair, if you are using regular expressions where you could be using a str_replace – then that’s a mistake in itself… there are certain things that you can do with regular expressions that you can’t with a str_replace, its not an either or situation – they are for different tasks.

  146. 146
    adu
    December 2nd, 2008 12:49 pm

    @Oliver (comment #5): totaly agree with you

  147. 147
    ewancoo
    December 9th, 2008 6:58 am

    (Reply to comment #6, #10)
    There is a huge difference between and . Double quotes scans for variables inside the string and interprets them (replaces them with the value). While single quotes do not consider variables inside the string, and thus returns the string as is.

  148. 148
    bullshit
    December 9th, 2008 8:30 pm

    to protect against sql injections use the placeholder, which is a component of DbSimple: http://en.dklab.ru/lib/DbSimple/ actually use the whole thing, save lots of development time dealing with sql

  149. 149
    theFreakus
    December 11th, 2008 2:39 am

    stop writing articles on matters you don’t know shit about. You are leading people, who are trying to learn PHP in a completely wrong direction. Some of the tips are unneccesary and most are simply bullshit.

    yours
    theFreakus ;)

  150. 150
    KevinMitnick
    December 26th, 2008 10:21 pm

    Typ-o in xmpl 6, 1st code shwz “$todo”, wyl 2nd shwz “$action”. Myte confuze sum n00bs! Gud artkl, luvd the sql-inject cheats.

  151. 151
    trs21219
    January 13th, 2009 6:29 am

    i agree with them all except for dropping the brackets…. that can lead to alot oh headaches and makes the code alot less readable. id rather spend the .05 seconds pressing that extra key than have to sort through a ton of code looking for the line i want

  152. 152
    Thomas Scholz
    January 18th, 2009 11:36 am

    You’re continuing your bad advices series from your latest wordpress article. What a pity.

    Please, focus on your »these are nice websites« content. Or get someone who reviews your articles before you press that big dangerous »publish« button.

  153. 153
    Bijay Manandhar
    January 29th, 2009 1:44 am

    USEFUL !!

  154. 154
    Jeff
    January 29th, 2009 9:56 am

    Will cleaning up simple warnings and notices (i.e. undefined property) produce a noticeable speed up?

  155. 155
    elances
    January 31st, 2009 1:54 am

    I’m sorry but the understanding of the “===” Operator or the beware of SQL-Injections are Advanced PHP Tips?? wth?

    Whats about Class-Autoloader, use of Design Patterns, the use of phpdoc comments, and the reading and understanding of the infamous paper from the owasp, “top 10 security issues in web applications”? I think that are better Tips then yours for PHP Developers.
    Most of that are Code-Design decisions and its obvious for every big project to create Code-Design-Guidelines and they would forbid the most of your “Tips”.

  156. 156
    KANG Ghee Keong
    February 17th, 2009 9:15 pm

    For performance in any program, worry about big-O, and about the algorithm. And if you need to do even more, move on to profiling, finding out where the bottle neck is before doing the final micro optimizations.

    This thread is about the longest I have ever read, with lots of constructive advises and dumb comments as well. Very entertaining to say the least.

  157. 157
    David
    March 11th, 2009 9:20 am

    Ternary operators are bad, period. The proof is in the article itself. The author states that:


    $todo = (empty($_POST[’todo’])) ? ‘default’ : $_POST[’todo’];

    is identical to:


    if (empty($_POST[’todo’])) {
    $action = ‘default’;
    } else {
    $action = $_POST[’todo’];
    }

    Well, it’s not.

  158. 158
    Tom Godar
    March 24th, 2009 11:23 am

    Advanced? Hah

    I agree with Matthew Weier O’Phinney’s comments.

    Write code that is readable. We sure it’s a good idea to introduce these people to a goto command? If I start having to re-factor spaghetti code I may just become a C# developer.

  159. 159
    stoimen
    March 25th, 2009 10:36 pm

    Nice post! Great job.

    good luck

  160. 160
    AskApache
    April 5th, 2009 1:50 am

    Ya these are pretty weak tips… I don’t consider myself advanced and I KNOW these aren’t advanced.

    Ternary = good. (bad examples)
    Framework = iffy/defaults to bad.
    memcache = do it right first-time, you won’t need it.
    @ suppression = good
    drop the else? perfect place for a ternary.
    sql cheatsheet? ahhh.. im going to the rebuttal!

  161. 161
    php_pro_69
    April 6th, 2009 5:30 am

    hi, im sorry, the advanced tips were where?

  162. 162
    Sergey
    April 17th, 2009 8:05 am

    $albert = @$albus; // this way is VERY BAD for performens

  163. 163
    Kevin
    April 22nd, 2009 3:33 pm

    Hi. We do not believe if we do not live and work according to our belief.
    I am from Jamaica and learning to read in English, tell me right I wrote the following sentence: “A wall clock with a visible pendulum and simple or complex striking train onto are some examples of wall clocks with pendulum movements – return to.”

    Best regards :D, Kevin.

  164. 164
    Anna
    April 23rd, 2009 9:56 am

    Ternary operators, shortcutting the else and dropping brackets make your code easier to read? It’s a matter of personal preference really. I can read code much better WITH curly braces and WITHOUT shortcuts. I just hate it when I have to debug someone else’s code that uses shortcuts everywhere. Save a character here, save a line there, and I’ll tell you to debug your code yourself.

    Less to debug with a framework? That is mostly true. But what if the framework has bugs in it? How much time do you save then? I’m not saying all frameworks are crappy, but I had to debug ZF once and it took me quite some time.

    This article is misleading and subjective.

  165. 165
    Rocky
    August 18th, 2009 7:33 am

    Some of your tips are just plain stupid to be honest you should not post any more articles untill u know what u are on about how dose posting bogus tips in your articles help upcoming or prolific designers

    I suggest you read up on the topic of your post before you post

    Have you even herd of google? how about insted of posting rubbish you do a little research

    I am not saying that your article isnt helpful its just a bit misinformed and that really needs to change.

    How about you go back and refine this post!

  166. 166
    Praveen
    September 15th, 2009 1:54 pm

    nice artical

  167. 167
    Jeff Jing From China 景振
    September 20th, 2009 5:42 am

    I think it’s stupid that this webpage is too long.
    But the article is really good. Contact Me:hndxjz@163.com

  168. 168
    Abiud
    September 24th, 2009 3:06 am

    Hi
    This really good tips. I am one guy who values optimal and compact code and to me , this should take precedence over any other consideration especially when building applications where memory use and management is vital.

  169. 169
    Rémi
    September 25th, 2009 11:48 am

    To the article author: Check at the bottom of the link you gave for the 10th point:

    Apparently the sarcasm of this blog is failing for many readers, so I added this disclaimer: IT IS SARCASM, USE STRLEN.

  170. 170
    Ashley Sheridan
    September 30th, 2009 11:15 am

    I’d argue the postscript note you have on number 6. PHP doesn’t get confused no matter what level of nesting you’ve used on your ternary operators. The only time you might see the PHP parser stumbling over complex nested ternary blocks is when you’ve messed up the coding. I have used nested blocks which go up to 3 deep before, without any problems. Admittedly when your ternaries get that nested, the code becomes harder to read, and you’re probably better off using regular if/else blocks. It is probably this ‘hard to read’ element which is causing the problems, as you end up missing brackets and all sorts. Don’t blame the tools!

  171. 171
    Voizle
    October 7th, 2009 11:17 pm

    Too good…

    and very nice tricks.. related to performance.. which generally people.. forget.. or dont consider it…

    Thanks
    Voizle

  172. 172
    Ricarda
    October 18th, 2009 2:59 am

    Could you help me. Only dull people are brilliant at breakfast. Help me! It has to find sites on the: Medigap health plans. I found only this – medigap basics. Policies with medicare with american or imperative interest can incur routine lush treatment in increasing the enforcement, eligibility, able and important relevant deductible benefits. This medigap of funds provides the retirement to keep forms assigned by out-of-pocket increases.If somewhat, they will apologize days if they help later. THX :-(, Ricarda from Brunei.

  173. 173
    hadi
    November 16th, 2009 1:46 am

    This is quite excellent and most of them i use. So many many thanks for the tips

  174. 174
    Nicolas
    November 20th, 2009 2:55 am

    I’m againts some parts of “Drop those Brackets”…
    This is a good way to mess completly your code when using shortcuts like :
    if ( $a == = true ) do_something();
    else do_otherthing();

    It can make your code difficult to read. Just be consistant with standard and prefer readability over compacticity :)

    If you still prefer use it, then use it wisely …. and use indent then :
    if ( true )
    do_something();
    else
    do_otherthing();

    Sorry for my poor English.

  1. 00

    There are no trackbacks at this time. If you are interested in leaving a trackback, please use this URL.

Leave a Comment

Make sure you enter the * required information where indicated. Please also rate the article as it will help us decide future content and posts. Comments are moderated – and rel="nofollow" is in use. Please no link dropping, no keywords or domains as names; do not spam, and do not advertise!



Advertisement Advertise with us!
Join in Smashing Forum
  • Re: Correct way to learn PHP

    Start off by reading all the 15 parts of PHP 101 on Devzone.

  • Re: Using Tutorials?

    I say you're okay. I wouldn't straight up jack someone else's design and present it as my own, even if it was a tutorial, but it's certainly acceptable to learn some…

  • Correct way to learn PHP

    So, I'm a designer but I wanna expand my abilities and learn PHP, to be more exact I wanna learn CI - Codeigniter!

  • I wanna make comics!

    Hello,I'm designer but I've never involved in vector painting so I need your help

  • Re: Twitter

    @gatorwebdesignShould tweet something really...

Post your job