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)

Footnotes

  1. 1 http://www.smashingmagazine.com/2009/03/24/10-useful-php-tips-revisited/
  2. 2 http://en.wikipedia.org/wiki/PHP
  3. 3 http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/#AboutMySQLandPHP
  4. 4 http://en.wikipedia.org/wiki/SQL_injection
  5. 5 http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/#AboutMySQLandPHP
  6. 6 http://docs.php.net/manual/en/language.operators.comparison.php
  7. 7 http://docs.php.net/manual/en/language.operators.comparison.php
  8. 8 http://ioreader.com/2007/08/17/11-cool-things-about-php-that-most-people-overlook/
  9. 9 http://docs.php.net/manual/en/language.operators.comparison.php
  10. 10 http://us3.php.net/else
  11. 11 http://www.christianmontoya.com/2007/11/09/php-techniques-i-use-all-the-time/
  12. 12 http://evolt.org/these-things-i-know-php-tips
  13. 13 http://evolt.org/these-things-i-know-php-tips
  14. 14 http://us.php.net/manual/en/function.str-replace.php
  15. 15 http://us.php.net/manual/en/function.ereg-replace.php
  16. 16 http://us.php.net/manual/en/function.preg-replace.php
  17. 17 http://www.phpvalue.com/what-is-php-ternary-opeartor/
  18. 18 http://www.danga.com/memcached/
  19. 19 http://www.danga.com/memcached/
  20. 20 http://us3.php.net/memcache
  21. 21 http://www.cakephp.org
  22. 22 http://www.cakephp.org
  23. 23 http://framework.zend.com/
  24. 24 http://www.symfony-project.org/
  25. 25 http://codeigniter.com/
  26. 26 http://us2.php.net/operators.errorcontrol
  27. 27 http://michelf.com/weblog/2005/bad-uses-of-the-at-operator/
  28. 28 http://blog.dynom.nl/archives/String-length-vs-isset-to-check-string-lengths_20070807_5.html
  29. 29 http://blog.dynom.nl/archives/String-length-vs-isset-to-check-string-lengths_20070807_5.html

↑ Back to top Tweet itShare on Facebook

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

Advertisement
  1. 1

    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

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

    4
  3. 303

    USEFUL !!

    0
  4. 454

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

    2
  5. 605

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

    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.

    1
  7. 907

    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.

    2
  8. 1058

    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.

    1
  9. 1209

    Nice post! Great job.

    good luck

    0
  10. 1360

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

    hi, im sorry, the advanced tips were where?

    3
  12. 1662

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

    0
  13. 1813

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

    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.

    1
  15. 2115

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

    nice artical

    0
  17. 2417

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

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

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

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

    Too good…

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

    Thanks
    Voizle

    0
  22. 3172

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

    0
  23. 3323

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

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

    why dont you put more sir?

    0
  26. 3776

    Senthil Loganathan

    March 11, 2010 2:45 am

    Excellent article

    0
  27. 3927

    Thanks for the excellent article

    0
  28. 4078

    i feel like now im ready to go big

    0
  29. 4229

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

    Nice and interesting

    0
  31. 4531

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

    0
  32. 4682

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

    1
  33. 4833

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

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

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

    1
  36. 5286

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

    0
  37. 5437

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

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

    Awesome tricks.. Great Knowledge sharing… :)

    0
  40. 5890

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

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

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

    Nice article.

    1
  44. 6494

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

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

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

    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

    2
  48. 7098

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

    5
  49. 7249

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

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

    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…

    1
  52. 7702

    php compile ” ” but not compile ‘ ‘

    -1

↑ Back to top