nav-left cat-right
cat-right

Ten PHP Best Practices Tips that will get you a job

The last couple of weeks have been quite the experience for me. I was part of a big layoff at my former company, which was interesting. I've never been in that position before, and it's hard not to take it personally. I started watching the job boards, and a nice-looking full-time PHP position caught my eye, so I sent out a resume and landed an interview. Before the face-to-face portion, I chatted with the owner and head programmer on a conference call, and they ended up sending me a technical assessment quiz. One particular question caught my eye on this quiz… it looked something like this:

Find the errors in the following code:

<?
function baz($y $z) {
	$x = new Array();
	$x[sales]  = 60;
	$x[profit] = 20:

	foreach($x as $key = $value) {
		echo $key+" "+$value+"<BR>";
	}
} 

?>

So, give it a shot. How many can you find?

If you got the missing comma in the parameter list, the "new Array()" error, the colon instead of a semi-colon, the '=' instead of '=>' in the foreach statement, and the erroneous use of '+' on the echo line, then congratulations, you found all the errors! You have the basic PHP technical skills to pay the bills.

That's not how I answered the question though. I noted the errors, obviously, but I went further than that. For instance, did you notice that there were no single quotes around the array indexes ($x[sales] and $x[profit])? That won't cause a fatal PHP error, but it is a coding error! Did you also notice the use of double-quoted strings instead of single-quoted strings on the echo line? Or the usage of the opening PHP short tag? Or the usage of "<BR>" instead of "<br/>"?

After pointing out the actual errors, I made a point of adding comments about those things I just mentioned. It was enough to push the answer from "correct" to "impressive", and it scored me a lot of points with the programmers who were reviewing my application. Enough so that they offered me the job! (I eventually turned it down, as I have been seduced by the siren call of the contracting life, and I intend to flex my PHP skills to the benefit of my clients, and not a faceless corporate overlord who dabbles in telemarketing. I need a shower).

So, read on for my Ten PHP Best Practices Tips that will get you a job:

1. Single-quoted strings are your friend. When you surround a PHP string in double quotes, it is subsequently parsed by the PHP interpreter for variables and special characters, such as "\n". If you just want to output a basic string, use single quotes! There is a marginal performance benefit, since the string does not get parsed. If you have variables or special characters, then by all means use double-quotes, but pick single quotes when possible.

2. String output. Which line of code do you think runs faster?

print "Hi my name is $a. I am $b";
echo "Hi my name is $a. I am $b";
echo "Hi my name is ".$a.". I am ".$b;
echo "Hi my name is ",$a,". I am ",$b;

This might seem weird to you, but the last one is actually the fastest operation. print is slower than echo, putting variables inline in a string is slower than concatenating them, and concatenating strings is slower than using comma-separated echo values! Not only does not-inlining your variables give you a performance boost, but it also makes your code easier to read in any editor that has syntax highlighting (your variables will show up in nice colors). The little-known use of echo as a function that takes a comma-separated list of values is the fastest of them all, since no string operations are performed, it just outputs each parameter. If you combine all this with Tip #1 and use single quotes, you're on your way to some finely-tuned strings.

3. Use single-quotes around array indexes. As you saw in the quiz question above, I pointed out that $x[sales] is technically incorrect! You should quote associative array indexes, like so: $x['sales']. This is because PHP considers the unquoted index as a "bare" string, and considers it a defined constant. When it can't find a matching symbol for this constant in the symbol table however, it converts it to a real string, which is why your code will work. Quoting the index prevents this constant-checking stuff, and makes it safer in case someone defines a future constant with the same name. I've also heard that it is up to seven times faster than referencing an unquoted index, although I haven't tested this. For more on this, see the section called "Array do's and don'ts" in the Array section of the PHP manual.

4. Don't use short open tags. Eww… are you really using these? <? is just bad form. It can cause conflicts with XML parsers, and if you ever distribute code, it's going to annoy the heck out of people who have to start modifying their PHP ini directives to get it to work. There's just no good reasons to use short open tags. Use the full <?php.

5. Don't use regular expressions if you don't need to. If you're doing basic string operations, stay away from the preg and ereg function groups whenever possible. str_replace is much faster than preg_replace, and strtr is even faster than str_replace! Save those crunch cycles… your enterprise applications will thank you.

6. Don't use functions inside a loop declaration. This isn't a PHP-specific tip, but you'll see it in a lot of code.

Bad:

for ($i = 0; $i < count($array); $i++) {
//stuff
}

Good:

$count = count($array);
for($i = 0; $i < $count; $i++) {
//stuff
}

That should be pretty self-explanatory, but it's amazing how many people would rather save a line of code at the expense of performance. If you use a function like count() inside a loop declaration, it's going to get executed at every iteration! If your loop is large, you're using a lot of extra execution time.

7. Never rely on register_globals or magic quotes. register_globals and magic quotes are both old features of PHP that seemed like a good idea at the time (ten years ago), but in reality turned out to be not that great. Older installations of PHP would have these features on by default, and they cause security holes, programming errors, and all sorts of bad practices, such as relying on user input to create variables. Both these features are now deprecated, and everyone needs to stop using them. If you are ever working on code that relies on these features, get it out of there as soon as you can!

8. Always initialize your variables. PHP will automatically create a variable if it hasn't been initialized, but it's not good practice to rely on this feature. It makes for sloppy code, and in large functions or projects can become quite confusing if you have to track down where it's being created. In addition, incrementing an uninitialized variable is much slower than if it was initialized. It's just a good idea.

9. Document your code. You've heard it many times, but this can't be said enough. I know places that won't hire people who don't document code. I even got my previous job after an interview where the VP sat-in with the interviewer and I, where I had brought my laptop in and I was just scrolling through some code I had written for one of my sites. He saw my documented functions and was impressed enough to ask me about my documenting habits. A day later I had the job.

I know a lot of self-declared PHP gurus out there like to pretend that their code is so good that they don't have to spend time documenting it, and these people are full of $largeAnimal poop. Learn docblock syntax, familiarize yourself with some PHP Documentation packages like phpDocumentor or Doxygen, and take the extra time to do it. It's worth it.

10. Code to a standard. This is something that you should ask potential employers about during interviews. Ask them what kind of coding standards they use… PEAR? Zend? In-house? Mention that you code to a specific standard, whether it be your own, or one of the more prevalent ones out there. The problem with loosely-typed languages like PHP is that without a proper coding standard, code tends to start looking like huge piles of garbage. Stinky, disgusting garbage. A basic set of rules that includes whitespace standards, brace matching, naming conventions, etc. is a must-have, must-follow for anyone who prides themselves on their code quality.

That being said, I hate all you space-indenters. I mean, what the hell? 4 space characters as an indent? That's exactly four times as much whitespace to parse as a tab. More importantly, you can set your tab-stops to any value you want if you're using any text-editor more advanced than Notepad, so every developer can having something that they like the looks of. Set it to 4 if you want, or 0 if you're a masochist. I don't care, but you can't do that with spaces! You're stuck with exactly the amount that Mr. Monkey Pants in cubicle 17 decided to put in. So why are spaces so popular? This "4-space indent" standard everyone uses is stupid! Stop it! Stop doing it!

… sorry, pet peeve.

Anyway, I hope these tips are helpful. If you want to impress at a job interview, it's the little details that will get you noticed! Maybe don't rant about your coding standards though.

  • Digg
  • del.icio.us
  • DotNetKicks
  • Slashdot
  • StumbleUpon

153 Responses to “Ten PHP Best Practices Tips that will get you a job”

  1. ZigPress says:

    For once a really good PHP article found via Stumbleupon – quite rare these days :)

    I don't care what Pear or Zend say about using spaces – they're simply wrong. And Pear and Zend don't have the monopoly on coding standards anyway, nor are they religions to be blindly followed.

    All good code editors can convert one to the other (NotePad++ being one shining example), and all good file comparison tools (WinMerge being my fave) can ignore space/tab mismatches.

  2. djpate says:

    I'm tired of people dissing people that uses short tags.

    I mean come on, the xml problem is not one and when you have to do some quick echo's

    is really more convenient…

  3. djpate says:

    my php got removed

    I'm tired of people dissing people that uses short tags.

    I mean come on, the xml problem is not one and when you have to do some quick echo's

    <?=$var;?>

    is really more convenient…

  4. Carl says:

    I've had problems from code with short tags before. The biggest problem is that it's not easy to spot when it happens if you don't use them yourself and you're not set up to allow them.

    They kind of just feel wrong as well, in the same way that using really short, non-descriptive variables feels wrong.

  5. nuno costa says:

    I disagree with you on comments.

    I've written about this (http://www.francodacosta.com/blog/development/dont-comment-your-code), sorry for the pub, but here is what I think about comments!

    I think the code one writes should be clear enough so anyone can understand it.

    Commenting every line of code, is bad, and only makes the code harder to follow.

    I do think however that you should document what that code block is doing, but not every line!

  6. soeperees says:

    @djpate:
    <?=$var;?> is NOT convenient. It means you are mixing PHP with HTML witch is concidered bad practice in common.

    @Blake: Good article!

  7. sandrar says:

    Hi! I was surfing and found your blog post… nice! I love your blog. :) Cheers! Sandra. R.

  8. megan fox says:

    Sign: umsun Hello!!! rcuwwymhyw and 4369ssgfhphzye and 647I like your blog. cool post!

  9. [...] 英文原址:Ten PHP Best Practices Tips that will get you a job [...]

  10. Indranil says:

    I just came across this post, and while they're nice beginner advice, I'd hate to see guys get a job if all they have to do is avoid these 10 steps! I mean, these are pretty basic steps…

    Nice write-up nonetheless..

  11. Just Me says:

    I can't believe these are the 10 BEST practices.

    #1 should always be understanding your users and your goals.

    I've worked with many people who had "good habits" that write sucky code, and have frustrated users.

    My comments are few, but my code reads like natural language. NOBODY should looks at your code and think "What the heck does this do?"

    Treat your users like customers. They will come to your defense when the layoffs start.

    I hate one of our smart-ass IT guys who knows all the technical goodies but treats users like crap. He was just bumped off of my project, and will hopefully be bumped out of the company.

  12. Carl says:

    @Just Me

    While I agree with your take on coding, I'm slightly amused that you're calling someone out for being a smart-ass while at the same time being a smart-ass about "best practices."

    I'm sure you're fully aware that it's a popular figure of speech that roughly means "standard guidelines that work well."

  13. Matt says:

    I can understand this causing massive debate. I don't give a shit no more because I program one way and another at work. Who really cares anymore?

  14. Kit says:

    I think the biggest error in the code that your interviewer have given you is the function's logic. You're passing in $y and $z, but they're never used inside the function. You should only pass in things that you directly needs.

  15. Unni says:

    Very nice post…there are lots of best php practices articles out there in the web..this one among the good ones..but these tips are not always enough for someone 2 get hired..different companies have their own way of interviewing…but this definetly covers the basic ones and i still dont follow a couple of points above…but have to start implimenting in my codes…thanks for the tips…i really do agree with documentation,using function inside looops n all are really good tips..keep posting like this often..hope to see more from you..keep moving…

  16. Unni says:

    And ofcourse your domain name is very interesting phpvs.net…domain name very well synched with the tld .net hehe..nice ..

  17. Of course $x = new Array(); is not explicitly wrong – the class Array may have been defined somewhere else. The same goes for the $x[sales] line – sales may be defined as a constant somewhere.

  18. It's really useful resource.
    I liked it.

  19. Leonardo says:

    About the Indentation, have you read the Pear Standard? http://pear.php.net/manual/en/standards.indenting.php

    Anyway, I agree with you, but TABs are not always the best idea.

    What I do is I use @ so that way it looks better and at the same time it adds an encriptation look. Sweet.

    Just kidding hehe :)

    Thanks for the article.

  20. jun says:

    @Mark Skilbeck

    you could be right but you know you are only given those codes and nothing else. So Logic dictates that it's wrong because there's no Array class declaration in the code, same goes to sales. cheer's

  21. Ceb says:

    Those steps are more like 10 things to do to not look like a noob in an interview, but it's still a good article.

  22. [...] Ten PHP Best Practices Tips that will get you a job [...]

  23. Surendra says:

    This is an awesome article and as a programmer i don't find use these small mistakes.

  24. sateeshpatil says:

    Good, Need to have such articles ,,,,,,

  25. Steven says:

    The problem with using tabs instead of spaces is that one developer will use 4 spaces for a tab and another developer will use 3 or 8 spaces. Now no matter what number of spaces you set the tab setting, you cannot get the file to be properly indented.

  26. EllisGL says:

    @Steven I keep seeing code that uses spaces and tabs. *cringes*

  27. muhkuh says:

    Ah the myth about single quotes that are faster than double quotes. Have you profiled the code?

    It WAS true with php 3 and early versions of php 4 but please stop to spread these myth!

    The article is good but when you say things like "use feature X instead of Y because it is faster!" then please proof it!

    Anyway I totaly agree with regex functions versus standard string functions. As long as you don't check the format of an input use standard string functions. And when you want to check the format of input consider the filter functions before you consider regexes!

    I agree also to nuno costa. Don't overcomment the code only document the code that needs it (Like a algorithm) and document you classes/functions. But I think thats what you've meant.

  28. fuxximus says:

    i've read your article, having played around with PHP for the last 5 years, i can't agree with you more, i just think most are gimmicks. I personally pay attention to all of the things you mentioned, and it annoys me to hell when people i work with don't consider as important.

  29. Great article. However, there is an error in your section about loops.

    Using count($array) inside a for() statement will actually only execute the count function once, thus rendering a pre-defined variable quite useless.

    for() evaluates the three parameters in full before looping through the code between the braces, so it doesn't matter how you pass the data to the construct. You could use return variables from functions for all three parameters without impeding performance.

  30. Friends, I'm choosing to attack the naysayers of the tab movement. It's the absolute, most basic of mathematic principles: four bytes consume more bandwidth than one. So every time you use a space in your rendered code, you're adding a byte to the bandwidth overhead.

    So if you have a line of code with six levels of indentation, you're looking at either six bytes (tabs) or twenty-four bytes (spaces…if they're set at four).

    We shave single characters in src attributes by renaming 'this-is-the-best-photo.jpg' to 'titbp.jpg'.

    While it seems like nitpicking, I just can't abide uninformed commentary.

  31. And Muhkuh, kindly stick to your guns: in one sentence you bash the author for not providing proof of single- vs. double-quoted strings……and then you offer up some B.S. about regexes (which is true, by the way) without offering any sort of benchmarking whatsoever. Hypocrisy stinks.

    This is a good, solid list of "don't dos" that will benefit a whole lotta peeps.

  32. jamie says:

    Good post. I'm a beginner and I found this very helpful, especially the array tip.

  33. Ryan says:

    You know, on number 6, you could do:

    for($i = 0, $count = count($array); $i < $count; $i++) {

    }

    This both defines it once (rather than defines it every loop) AND saves a line of code! =D

  34. L says:

    @ Tony Parrillo

    "It's the absolute, most basic of mathematic principles: four bytes consume more bandwidth than one. So every time you use a space in your rendered code, you're adding a byte to the bandwidth overhead."

    Even I, who never actually wrote more than a few lines php in my life, know that this is so completly wrong.
    So I added some spaces to my php code. Does the code ever get send to anyone? No, it's interpreted on the server, no user will ever see that tab or spaces! There is no bandwidth overhead. Learn the basics.

    Now don't tell me that it takes longer to interpret. It's the same thing like your 'this-is-the-best-photo.jpg' vs. 'titbp.jpg'. You've got to realize that the sum of the time it is saving your users over the years is nothing compared to the time you've spend on renaming all those files.

  35. Andrew says:

    @L

    Tony specified "rendered code" (HTML), not PHP code. Maybe if you wrote more than a few lines of code, you could spot the difference. :P

    Also, don't forget file size is increased as well as bandwidth usage. Personally, I would agree that it's negligible. I prefer tabs because the tab width can be defined as whatever you want, and the next person that opens it can use a different tab width if they choose.

  36. L says:

    Ok, seems I didn't read that carefully :)

  37. devnull says:

    i am a tabber. i see no reason to use spaces, that is nonstandard. have your editor just use tabs, that is what the tab is for. why insert spaces instead of tabs, it is silly. i am not here to offend, but i have had my fill of this debate after 12+ years of coding.

    my personal feeling is, that if you are converting tabs to spaces you are just avoiding the tab character. set your editor to indent it how you like, but use tabs … im sorry i can't get past this .. that is what it is for, not spaces. it makes no sense at all to me.

    once again, not to offend … but there is no reason to replace a single character with multiple characters for no good reason.

    i can't remember but how would python handle the spaces v tabs issue ?

  38. You also appear to be a "lowercaser", in addition to being a "tabber".

    If you are so interested in standards, why not use the standards for the English language?

    It would mean at the very least people like myself couldn't undermine your entire point with your own words.

  39. devnull says:

    not trying to offend o'connor …. but that has no relevance to the topic, but to make you feel better.

    Yes I know my editors can handle either standard, but in my own mind isn't that what the tab character is for ?
    If you would like to have a discussion on that instead of my ability to type in grammatically correct English that would be fantastic for everyone else.

    No, I am not entirely interested in standards, there is no standard for these things. Though there is a perfectly good display character called tab that is used for indentation. For the sake of not reinventing things it makes sense to use that character for indentation.

    You didn't undermine any point of my previous posted comment. I suppose you took the comment I had made personally and had to respond out of anger. Grow up.

  40. devnull says:

    Remove the last 2 lines of my previous comment O'Connor.
    I would rather be friends than enemies. Seriously, I'm not hear to offend and I apologize for those last lines. It was out of line.

  41. Anger? No. I'm trying to merely point out that if you take the same approach to writing your code as you do to writing a comment on a blog entry, I think collectively we're better off without your contributions.

    If you've been writing c-style code for 12+ years using tabs (and more specifically PHP); whilst taking a lackluster approach to how you approach things, which I base entirely on your original comment, I'm very frightened of ever having to work with your code.

    I cannot think of a collection of developers who advocate tabs over spaces once they hit the different-editor-displays-differently issue.

    Not one.

    If you know of any, please do let us all know.

    Given your support for tabs over spaces, I'm assuming you've never encountered the different editor problem with others in your team – again, I'm very frightened of your code if this issue has never come up.

  42. devnull says:

    The way editors work is you can set the tab display width. This makes the difference to be not an issue. If you replace tabs with spaces than it will always be that many spaces. Now you would have to have a default amount of spaces to use between everyone to keep it the same.
    Tabs may look different on one persons screen than anothers but they are still tabs and you can adjust the display width. If they are spaces, they will always be spaces. That is the difference.
    Like I said, in the years I have been doing this, tabs have never been an issue. The only issue is when someone else is using spaces.
    I don't understand how tabs, which is a single character could create a problem. If you don't like the spacing adjust it.

    If editors display them differently it is okay. They will still be standard across the page and then you can change it. If one person likes them to look like two spaces, they can make it so. If another likes four, they can make it so. None the less it does not change the document.

    Can we agree that tab display is a setting that can be adjusted, therefore display differences are just that, display differnces and not structural differences?

    I don't have a huge problem with spaces, but tabs are always tabs, and spaces are always a single space. The amount of space a tab represents is relative to your preference but space is always a single character. I can't go into all of my editors and convert two spaces to four, but I can always change a tab to the spacing I want it to be.
    And (bad grammar) I don't care if your editor shows a tab to be four spaces and mine eight or two. That doesn't make the document different, that is just a setting. If that is what you are talking about as looking different, than is is not a good reason to not like tabs because you can change that easily. How a tab looks to me compared to someone else isn't my concern.

    (sorry for any errors … Typing on my phone)

  43. OldGeek says:

    Tab vs space is a stupid argument to be having. It's like braces on the same line or on the next line… yes you can set a tab stop or configure the width of your tabs. That's all fine and good. There are also these new-fangled things called formatters that most decent code editors have and they format your code according to a standard rather than the way you typed it.. EUREKA!

    However, I find the most hilarious argument in here the idea that a tab takes up more bandwidth than a space. The commenter who says it never makes it to the browser is 100% correct. WTF are you doing formatting html? That's got to be the worse excuse for spending time writing code I've ever heard of.

    The only way tabs could make a difference bandwidth-wise is if you are submitting to source control. However, if the network compresses the data, all the whitespace will be compressed so it makes absolutely no difference whatsoever.

  44. Some good tips specially for a newbie.

  45. m4niac says:

    Thanks for the great article!

  46. mhitza says:

    For some parts of it I agree (like short tags and register globals) but micro optimizations and stuff like " vs "… come on… that has nothing to do with PHP.

  47. Ten PHP Best Practices Tips that will get you a job…

    Ten PHP Best Practices Tips that will get you a job….

  48. Azad says:

    It's really useful resource.

Leave a Reply