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 article1 instead of this article.

PHP programming has climbed rapidly since its humble beginnings2 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 Injection3
A list of common SQL injections.

SQL injection4 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 sheet5 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

Equality Operators6
PHP’s list of comparison operators.

Comparison operators7 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 reader8 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 operators9 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 statements10, so to speak. Christian Montoya has an excellent example11 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

Drop Brackets12
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 example13 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()

Str Replace
Speed tests show that str_replace() is 61% faster.

In terms of efficiency, str_replace()14 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()15 and preg_replace()16.

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

Memcached18
Memcached is an excellent database caching system to use with PHP.

While there are tons of caching options out there, Memcached19 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 memcached20 with your PHP projects.

8. Use a Framework

Framework21

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 CakePHP22, Zend23, Symfony24 and CodeIgniter25 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 operator26“) 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 examples27 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

Strlen28
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 strlen29:

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)

↑ Back to topShare on Twitter

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

  1. 1

    nice article

    -5
  2. 2

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

    5
  3. 3

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

    21
  4. 4

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

    1
  5. 5

    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.

    8
  6. 6

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

    Giovanni Battista Lenoci

    November 18, 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)

    -1
  8. 8

    Great but you should rename the post to:

    “6 adavanced tips to mess up your code!”

    -3
  9. 9

    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.

    -1
  10. 10

    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.

    2
  11. 11

    I don’t agree with the 4th tip.

    1
  12. 12

    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.

    2
  13. 13

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

    3
  14. 14

    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.

    2
  15. 15

    Thanks. PHP tips are always welcome!

    1
  16. 16

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

    -1
  17. 17

    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

    1
  18. 18

    great!!

    -2
  19. 19

    Amazing…….

    -2
  20. 20

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

    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.

    0
  22. 22

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

    0
  23. 23

    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!

    2
  24. 24

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

    Nice post.

    0
  25. 25

    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.

    -2
  26. 26

    troll ?

    1
  27. 27

    “Drop those Brackets” is a bad tip…

    1
  28. 28

    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.

    3
  29. 29

    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.

    1
  30. 30

    yupii symfony ;)

    1
  31. 31

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

    0
  32. 32

    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/

    0
  33. 33

    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.

    1
  34. 34

    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!

    0
  35. 35

    Matthew Weier O'Phinney

    November 18, 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.

    1
  36. 36

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

    0
  37. 37

    @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

    1
  38. 38

    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.

    0
  39. 39

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

    0
  40. 40

    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.

    0
  41. 41

    nice article

    0
  42. 42

    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.

    0
  43. 43

    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!!

    0
  44. 44

    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…

    0
  45. 45

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

    0
  46. 46

    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.

    0
  47. 47

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

    1
  48. 48

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

    1
  49. 49

    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.

    0
  50. 50

    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.

    0
  51. 51

    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.

    0
  52. 52

    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.

    0
  53. 53

    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.

    0
  54. 54

    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.

    0
  55. 55

    Laaangweilig!

    0
  56. 56

    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.

    0
  57. 57

    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.

    0
  58. 58

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

    0
  59. 59

    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 :)

    0
  60. 60

    Advanced programmer

    November 18, 2008 10:47 am

    Yay, Im an advanded programmer now!

    0
  61. 61

    @ 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).

    0
  62. 62

    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.

    0
  63. 63

    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!

    0
  64. 64

    @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!

    0
  65. 65

    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.

    0
  66. 66

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

    0
  67. 67

    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…

    0
  68. 68

    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…

    0
  69. 69

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

    0
  70. 70

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

    0
  71. 71

    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.

    0
  72. 72

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

    0
  73. 73

    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.

    0
  74. 74

    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.

    0
  75. 75

    “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!

    0
  76. 76

    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.

    0
  77. 77

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

    0
  78. 78

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

    0
  79. 79

    good article, thanks!

    0
  80. 80

    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.

    0
  81. 81

    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?

    0
  82. 82

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

    0
  83. 83

    Vitaly Friedman & Sven Lennartz

    November 18, 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.

    0
  84. 84

    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

    0
  85. 85

    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.

    0
  86. 86

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

    0
  87. 87

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

    0
  88. 88

    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!

    0
  89. 89

    duh. noob article.

    turd cassarole.

    frameworks slow down small site development by the way.

    0
  90. 90

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

    0
  91. 91

    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

    0
  92. 92

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

    0
  93. 93

    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.

    0
  94. 94

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

    0
  95. 95

    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.

    0
  96. 96

    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

    0
  97. 97

    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.

    0
  98. 98

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

    0
  99. 99

    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.

    0
  100. 100

    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

    0
  101. 101

    Nice Article…. Thanks You!

    1
  102. 102

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

    0
  103. 103

    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.

    0
  104. 104

    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!

    0
  105. 105

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

    0
  106. 106

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

    0
  107. 107

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

    0
  108. 108

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

    0
  109. 109

    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.

    0
  110. 110

    Martin Joergensen

    November 19, 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

    0
  111. 111

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

    0
  112. 112

    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’];
    }
    ?>

    1
  113. 113

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

    0
  114. 114

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

    0
  115. 115

    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.

    0
  116. 116

    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.

    0
  117. 117

    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.

    0
  118. 118

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

    0
  119. 119

    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

    0
  120. 120

    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.

    0
  121. 121

    This article should read x Comment Tips to Improve This Article

    LOL.

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

    0
  122. 122

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

    0
  123. 123

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

    0
  124. 124

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

    0
  125. 125

    @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)

    0
  126. 126

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

    0
  127. 127

    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.

    0
  128. 128

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

    0
  129. 129

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

    0
  130. 130

    very good reply

    0
  131. 131

    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 :(

    0
  132. 132

    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.

    0
  133. 133

    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.

    0
  134. 134

    Mark A Hershberger

    November 21, 2008 6:44 pm

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

    0
  135. 135

    Nice article. Thanks for the tips….

    0
  136. 136

    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

    0
  137. 137

    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!!!!

    -1
  138. 138

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

    0
  139. 139

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

    0
  140. 140

    Good entry :-)

    0
  141. 141

    Useless. It does nothing for home country.

    0
  142. 142

    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.

    0
  143. 143

    nice tips

    0
  144. 144

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

    0
  145. 145

    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.

    0
  146. 146

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

    0
  147. 147

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

    0
  148. 148

    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

    0
  149. 149

    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 ;)

    0
  150. 150

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

    0
  151. 151

    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

    0
  152. 152

    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.

    0
  153. 153

    USEFUL !!

    0
  154. 154

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

    0
  155. 155

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

    0
  156. 156

    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.

    0
  157. 157

    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.

    0
  158. 158

    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.

    0
  159. 159

    Nice post! Great job.

    good luck

    0
  160. 160

    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!

    0
  161. 161

    hi, im sorry, the advanced tips were where?

    1
  162. 162

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

    0
  163. 163

    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.

    0
  164. 164

    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.

    0
  165. 165

    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!

    0
  166. 166

    nice artical

    0
  167. 167

    Jeff Jing From China 景振

    September 20, 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

    0
  168. 168

    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.

    0
  169. 169

    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.

    0
  170. 170

    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!

    0
  171. 171

    Too good…

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

    Thanks
    Voizle

    0
  172. 172

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

    0
  173. 173

    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.

    0
  174. 174

    Hi dude,

    Amazing and gr8 explanation!All are familiar tips expect the memcache,ternary operator’s for me.By the way for my next project will try to keep up with all the tips

    So keep up the same pase!

    0
  175. 175

    why dont you put more sir?

    0
  176. 176

    Senthil Loganathan

    March 11, 2010 2:45 am

    Excellent article

    0
  177. 177

    Thanks for the excellent article

    0
  178. 178

    i feel like now im ready to go big

    0
  179. 179

    For those saying that dropping brackets is bad practice I have to add that in some instances it might be good practice and indeed improve readability and save space. As always it just depends on the situation. If statements are short and repetitive dropping brackets it’s a great thing if you ask me. Know the options and use them appropriately.

    1
  180. 180

    Nice and interesting

    0
  181. 181

    nice article. Thanks for publishing such a great article. Its really helpful.

    0
  182. 182

    #10 is actually a bad idea, see the article referenced. It was posted sarcastically.

    1
  183. 183

    Although this post is almost three years old, I decided to add my own thoughts, since this article is ranked first for “advanced php programming tips”.

    #1. SQL Injection
    Use parameterized queries (PDO). Generating queries with string concatenation is needlessly risky. Or at least properly escape user input. Don’t use addslashes!

    #4. Drop those brackets
    Always use brackets. You gain nothing by leaving them out.

    #9. Suppression character
    The examples given are not “equivalent”. The error suppression operator should only be used as a last resort. Read the documentation before using it. And assigning by reference to avoid a PHP Warning is just wrong and confusing.

    #10. Use isset instead of strlen
    This isn’t a tip and is just plain wrong.

    0
  184. 184

    Thanks for posting such nice thread and we learn many new things.

    As for as the comparison in this thread regarding PHP vs .NET, I would totally agree with PHP Techie as this language is going to be emerge as dominating language on web.
    As for as language selection is concerned you can’t say which is better, even though it all depends upon the individual who uses that language and how much secure code one writes.One of recent example is Facebook, one of most earning web portal , in PHP.

    So PHP techie just keep rolling and contribute more to opensource as you and see these .Net,Java will follow you soon…..
    Happy coding to all

    1
  185. 185

    I can’t argue with the wonderful content your blog has to offer and consequently I need to say thanks

    1
  186. 186

    it’s an useful article. i must keep evernote this :) thanks

    0
  187. 187

    Problem with removing brackets and using ternary operators is it makes it a lot harder to read. I don’t see the need to make PHP code so compact.

    3
  188. 188

    Thanks for writing the article. I do not agree with all pointers you gave but it’s a good article to newbies.

    However, I’d like to add something to the pointer you gave about if-else statements. Your example:
    $x = 10;
    if( this condition )
    {
    $x = 5;
    }

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

    0
  189. 189

    Awesome tricks.. Great Knowledge sharing… :)

    0
  190. 190

    What’s the point ? to save space or be efficient ? If you “shortcut the else” you will execute the first assignamet statement everytime, it has a cost, ok now do the same in every IF in your code :P

    0
  191. 191

    I work at a web/software firm with 9 other devs and I would get chewed out if I used most of those tips. A tip for developers starting out that and trying to find a job is to follow coding standards! A potential employer would prefer to see well structured and easy to read code over shortening it a few lines. Believe me, I was the worst for this and I got a lot of negative feedback while submitting a sample project to a web firm I was applying at. Do yourself AND your co-workers a favor by follow coding standards. There is no award for least lines of code. You don’t look like a programming ninja. Stop it.

    0
  192. 192

    Some of your infos are really good but i fully disagree with using a framework.
    Frameworks are great when you are in a project with hard deadline. But not for a High traffic website.

    0
  193. 193

    Nice article.

    1
  194. 194

    Looks like I failed to find the “advanced” part. I suppose this is all relative, however these are not very advanced topics. To me it sounds like a beginner wrote these tips. I didn’t see any mention of an object, PDO, design patterns, dependency injection, unit testing (TDD/BDD), etc… I understand this is an older article so maybe give it an update?

    0
  195. 195

    Nice post

    but there’s a mistake in the 6th point example

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

    should be this : `$action = (empty($_POST[’todo’])) ? ‘default’ : $_POST[’todo’]; `

    0
  196. 196

    A few of these are sacrificing readability for “shorter” code. It’s especially silly since shorter != a performance improvement. e.g. if you expect an if-else to evaluate true 99% of time on the if, then you’re wasting cycles with that assignment operator you keep executing then overriding. If you try and be smart and not the if statement first because it’s usually true, you end up with much less readable code.

    If you’re writing in PHP in the first place, you shouldn’t be writing code where that level of optimization is necessary. The whole point of php is to keep it readable.

    0
  197. 197

    You know what you are idiot…………..

    That’s why you say like that…………….

    PHP more better than ASP.NET/C#.NET

    and actually we are not funny you .NET people are cartoon

    3
  198. 198

    Grow up kid…. Get up from your “.NET” bed and see around… Its time for you to wakeup…

    5
  199. 199

    Deary me… You’re judging the whole PHP community and the language on one article and a few comments. First of all you can’t judge the language because of the way people use it; just because people don’t know the difference between comparison operators doesn’t mean it’s language’s (or the community’s) fault. Just because someone is suggesting not using brackets (I hate non bracketed btw), and other shortcuts doesn’t mean everyone does that.

    If you love .NET that’s fine, but don’t despise a whole language and community just because some people might write sloppy code.

    6
  200. 200

    ASP.NET people are drag and drop minds.

    I know a lot of ASP.NET programmers wihout any sense o creativity

    Im my language we call them: “Macacos de repetição” .. something like “Repetitions Code Monkeys.”

    Cause they can´t really CREATE new things.. they area perfect to do repeated tasks .. their minds are not focus on thinking the hole problem, becouse V.S. is allways helping then ( making them stupid for CREATION new tecnolgies )

    The reason you think u know it all it´s becouse V.S.´s wizards … Go DRAG !

    0
  201. 201

    Hey… Please concentrate on your .Net market Condition… You may have to turn towards PHP
    … My Better Suggestion for you is that start reading w3school.com PHP Tutorials…

    2
  202. 202

    php compile ” ” but not compile ‘ ‘

    -1

↑ Back to top