Jun 04 2008
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.
94 responses so far





Excellent article Blake,
though I found it interesting that you advocate the use of a coding standard, and I agree 100% with you. You recommend a couple of standards, PEAR and Zend, and one of the first things that both of those standards state is to use "4 space indentation, no tabs" in direct contradiction with your pet peeve.
Maybe if you work in only one platform it really makes no difference to use one or the other, but from personal experience, once you start transferring your files from unix to windows to linux, or collaborating within a team, those special characters might become problematic, specially if you need to do a quick edit with vi (yes, I still use it).
For those readers that want more coding tips, I recommend the book "Code Complete" by Steve McConnell, it is full of best practices that might not get you a job, but will definitely make you a better coder.
Anyway, keep up the good work and thank you for collaborating!
Hi Aldo,
Thanks for your comments! I'm going to defend my pet peeve here, don't take it personally
I know that most coding standards like to use 4 spaces, including PEAR and Zend, which is why it's my pet peeve.
The thing is, tab isn't really a special character at all. It's just another byte, same as a space or an 'A' or any other character. It just differs in how your text editor decides to display it.
The annoying part for me is that almost every text editor in the world, even the venerable vi (which I also use practically every day) has a tabstop setting. For instance, in vi, just use the command
:set tabstop=n, and voila! Better yet, create a file called.exrcin your home directory, and put the command in there (vi runs this file on startup). Customized tab stops every time! Great for terminal editors when you have limited window widths. Tabs shouldn't cause a problem when switching files between systems either, unless something funny is going on.So, my point is that if every coding-ready editor in the world has a tab stop setting, why use spaces? Some people like giant indents, some people like tiny indents. Some people like different fonts while developing, where tabs can be bigger or smaller depending on the font's kerning or base width. Maybe someone likes giant fonts for readability, but because they have giant characters, they want to use tiny indents to save screen room. If everyone used tabs, code would be easier for everyone to look at in their preferred format.
On the flip side, when I have to deal with the overseas team who decided to have a 6-level nested if/else block using only a single space as an indent (don't get me started here
), my eyeballs are going to burst from trying to mentally brace-match, and there's nothing I can do to re-format it except convert all the spaces to tabs.
Anyway, that's my side of the debate. I do realize it's not the common standard.
Oh, and thanks for the book recommendation. It looks like my local library has a copy, I'll have to take a look.
@Blake - You might not like my code then - I use single space indent. I also line up my equal signs per scope. Of course 6 level nested ifs are insane.
@Blake- ack clicked the submit too soon. I'm sick of dealing with projects that use PEAR. Download it, install it.. crap.. pear install xxx.. argh.. that module has been depreciated or has changed radically and isn't compatible. Makes me want to rant on another thing like that (*coughlinuxdependenciescough*). Oh well rant off..
Totally agree about tabs vs spaces. I see no reason to use spaces.
Hey Ellis, yeah I'm not a fan of PEAR either. It does tend to cause a lot of hassle sometimes, especially in distributed environments or large projects where module versions get out of sync.
I used to feel the same way about linux dependencies, but ever since I started using
yumthat's been less of an issue. A good package manager goes a long way towards the dependency problems, and yum offers features that beat out basicrpm.Fletch - another tab user! Yes! Maybe I should download a Wordpress poll plugin and get it going….
@Fletch: I've seen tabs appear different in different editors.
[...] siguiente es un buen artículo de como programar en PHP usando buenas prácticas. Empecemos a profecionalizarnos en el desarrollo [...]
[...] Eine ausf
[...] 10 Tipps f
Dear Blake,
I just read your article today (linked from it-republik.de). Some of your points are interesting but some of your points are also very "controversial".
Especially #2 (micro "optimization") and #3 in your posting from 11 Jun 2008.
I think when you are arguing that way on optimization(!) most companies with exprerienced programming teams will loose interest in you. Why? You are right on using "best practices" but "best practices" is not equal to "optimize right from the start".
There is a very interesting article from Donald Knuth, written in 1974, and still valid today, its conclusion:
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." (Knuth, Donald, Structured Programming, ACM Journal Computing Surveys, Vol 6, No. 4, Dec. 1974. p.268.)
But why is this? "Premature optimization" is a phrase used by Donald Knuth to describe a situation where a programmer lets performance considerations affect the design of a piece of code. This often results or can result in a design that is not as clean as it could have been or code that is incorrect, because the code is complicated by the optimization and the programmer is distracted(!) by optimizing. An alternative approach is a) to design first, b) code from the design and then c) profile/benchmark the resulting code to see what *should* be optimized. A simple and elegant design is often easier to optimize at this stage, and profiling may reveal unexpected performance problems that would not have been addressed by premature optimization.
Hi ingo,
I've run across that exact article before, and I disagree that experienced programming teams will lose interest in someone because they follow practices like the things I mentioned above. These tips are best practices - they are not instructions on how to optimize a PHP application. If I was given a PHP application and told to "make it faster", I wouldn't even bother going through and converting single quotes to double quotes or hunting for unescaped string indexes unless I had already profiled it and fixed everything else, and had a bunch of time left to waste.
On the other hand, if you follow best practices from the start, you end up with better, cleaner code with micro-optimizations in place. None of the coding tips I listed above take any extra effort to program, and they don't clutter up your code. They just show that you're familiar with the best way to use some features of the language!
Cheers!
Really, a good article, worth to read and spent time to read. Good tips are listed here and now it is totally depends on me which one relates to me. String concatenation vs comma saparation I first time came to know their execution time. Though documentation is my habit where ever required and I feel necessary I write comments in my code. Reading this article, I can guess I 'm running on right track.
[...] Diez trucos de codificación en PHP, orientadas a entrevistas de trabajo, en PHP vs .Net [...]
Hi Rajiv… good stuff! Thanks for your comment.
Apart from the obvious syntactical errors, it seems you missed the most important problem with that code. Whenever you embed strings into foreign code, you must escape it. No exceptions. So the line which echo, should be properly written as:
echo htmlspecialchars($key) . " " . htmlspecialchars($value) . "";
If you're concerned with micro-performance, then you shouldn't use string concatenation in this case btw. This is faster:
echo htmlspecialchars($key), " ", htmlspecialchars($value), "";
… not that it matters.
[...] baca artikelnya di sini dan di [...]
Another tabbed indenter here. Did you know that Notepad2 (which happens to be my favorite text editor for doing anything quick) has a "Tabify Selection" feature. That's right, spaces used for indentions are automatically turned to tabs. It also has an "Untabify Selection" for anyone who isn't cool enough to configure their tab preferences. I just noticed it a few weeks ago, and I wish Eclipse had the same thing.
Also, in your quiz, I know it's not a technical error, but I noticed that the function doesn't return anything. This just feels wrong to me.
And I also agree that knowing the ins and outs of a language and good coding practices, and being able to explain some of the lesser known details about it will win you points in a job interview.
If I was interviewing someone and they implied that any of the points you made were stupid to mention, I would wonder the following:
1. This person is difficult enough to speak to, how much harder will they be to work with?
2. This person does not get much personal enjoyment from PHP, and probably will not write code as good as someone who does.
3. Are they trying to cover up a lack of knowledge?
[...] Ten PHP Best Practices Tips (tags: php tips programming coding bestpractices best practices) [...]
[...] Ten PHP Best Practices Tips that will get you a job | PHP vs .Net. [...]
You mention about the Pear coding standards, and they actually use 4 spaces instead of tab:
Extract from the first few lines:
Use an indent of 4 spaces, with no tabs. This helps to avoid problems with diffs, patches, CVS history and annotations.
The only issues I found with diff were from a code that was committed with spaces and later converted to tabs. But you could also use "ignore whitespace" on your diff tool.
I just checked the Zend Framework coding standards and they also use 4 spaces..
B.2.2. Indentation
Indentation should consist of 4 spaces. Tabs are not allowed.
I also hate it.. but there must be another explanation, besides the diff.
Just wanted to drop by…found you through StumbleUpon. This was a great read! Easily readable even by an amateur at PHP.
I didn't bother reading all the comments … but just like to point out that:
$x[sales] = 60;
I wouldn't call the lack of quotes even 'technically correct'. It works simply because php assumes that an undefined constant has a value equal to it's name. You can see it in your logs if you ever do it … 'undefined constant 'sales', assuming "sales"' or something to that effect. There goes a bunch of E_STRICT i think (if not E_INFO)
er … please ignore my post. I will read the entire article next time.
well i wouldve gotten the job too.
I picked up all of the errors including the bad code practices too regarding the single and double quotes, and the ones missing from the brackets. I would have gotten the job as well.
If I were you I'd make a more harder OOP based one instead. Most places adopt a PHP OOP standard now as opposed to procedural.
Dwayne.
http://probablysucks.com
$x = array(
'sales' => 60,
'profit' => 20
);
Nice one. Am already use to all this but it's refreshing.
Anyine noticed the first error?
function baz($y $z) {
//Other stuff
}
The error is a missing comma btw the arguments of function baz.
Regarding #3, I must disagree with the people here who claim this is nothing but micro-optimization. I just ran across a bunch of old code in which the previous programmer had used bare strings instead of properly quoted array indices. The page was taking almost 28 seconds to load(!). After I optimized by converting these to quoted indices, the page loaded in microseconds. (There were six of these bare strings inside a while loop, five of them on a single line.)
Good article. Although, like others, I'd be worried about working any place where acquiring a job hinged on your being able to point out syntax errors that the IDE would catch. I'm not saying you shouldn't know them, but if a job is lost because you didn't notice a colon instead of a semicolon in one statement, I likely wouldn't want to work there to begin with (because it seems like the type of place where they would micro-manage, and put style over substance)
I don't really agree with the space vs tab thing, only because I use Python for a lot of projects, so using spaces is kind of my default. I'd say whatever you do, though, ALWAYS be consistent. Nothing is worse than looking at code where they mixed spaces and tabs.
However, when I was strictly working in PHP, Java, and other C-like brace-delimited languages, I used tabs over spaces (of course, I like my tabs to display as 2 spaces. Dunno why — 4 always seemed too "wide" for me).
As for the poster that said they like short open tags — I do too (I think everyone does), but I don't use them. If you move your scripts to a server where short tags are turned off, then your code won't work.
One thing I hate about not using short tags, though, is when you're embedding PHP in a simple HTML file. Having to type <a href="<?php echo $url ?>"> instead of the more concise (and easier to read) <a href="<?= $url ?>">
Hi, just popping by to let you know your article is still doing the rounds on stumbleupon and I thoroughly enjoyed your article, I'm sure those tips will make me a better php programmer.
[...] Ten best practices for php nos ayudará a optimizar y depurar el código con unas buenas prácticas y con Eight best practices podremos completarlas. También puede interesarnos Trucos, manuales y articulos Php. [...]
Tabs vs Spaces
You can't talk about indenting without taking into account the programming language. This is the mayor mistake people do in this area.
If anybody has read the original article (or post) against indenting with tabs, it was referring to LISP-like languages.
LISP-like languages are much better with ONLY spaces. Really. Indentation in them is just much more complex, and only editors like Emacs can do it well. You don't do it by hand.
C like languages are much better with tabs. A lot better, because everyone has a different preference for that. But, remember, to align chars after the indenting tabs, or anywhere in the rest of the line, you can or should use spaces.
Frankly, anyone arguing in favor of indenting ONLY with spaces, and speaking about C-like languages is a meme-repeating bigot, and annoys us, the programmers of C-like languages.
[...] yourself on code quality. Congratulate yourself with a feeling of superiority, regardless of at how many answers you peeked [...]
I am just about to take on the PHP programming language, thanks for these ideas!
comparison of some loops (100.000 iter.):
for(without count) 0.036905s
for(with count) 0.489252s
foreach 0.025493s
while 3.0E-5s
What is the dead of the good, the better.
for(without count) 0.036974
for(with count) -0.445548
while 0.036644
foreach 0.025445
What does the results above mean?
AVOID for-loops => use foreach unless you need an iterator for steps greater than 1.
do…while is faster from what I have seen. ~12% when applied to MySQL loop.s
Great article and I learned a few new things. This is definitely a site to book mark to help in my efforts to become a better programmer.
I am so with you on the tabs thing.
Would I rather press tab once and be able to shift code back with shift+tab or press space four times for each line….?
Also what happens when you select a block of code and press space 4 times? oops
Now try it with tab…
Who the hell came up with this standard!
Anyway excellent post I would love to read some OOP best practices next..
Cheers
[...] Ten PHP Best Practices Tips that will get you a job [...]
[...] Ten PHP Best Practices Tips that will get you a job [...]