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

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

  1. varun says:

    Regarding point 2:

    microbenchmarks are just that -"MICRO" benchmarks – and they seldom are of any significance .. You can corroborate this with Rasmus Lerdorf, Sara Golemon, …

  2. Frank says:

    Why do you contradict yourself in #2? You already recognized that the parser should/must not be bothered with strings that don't contain variables or other control chars.

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

    That's the way to go.
    In #6 you could also take this approach:

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

    That way $count does only exist within the for loop and is discarded from memory afterwards. One less variable to carry around.

  3. Hey,

    That was a great article to read. Most of the coding techniques that you describe in this I already put into place. Every PHP developer is different from another, so not all of these things I do. I have my own certain ways to get things done efficiently which are just as good.

    I'm not really a optimisation Nazi though. I do agree writing efficient code is the best practice. But in the case of small applications where such optimisations won't be necessarily helpful or even noticeable, I tend to write how it comes out and take the "If it works, don't tinker with it approach."

    This article is great in-sight for junior or mid-weight PHP programmers, you did a good job.

    - Dwayne Charrington.

  4. Don says:

    The $y variable in that function is never used. Seems like a error to me.

  5. Andrew says:

    Good tips – I missed the colon and the 'new Array();' parts, but that is what PHP's error reporting is for. :)

    I also agree with you on the tabs issue, although I wasn't aware that it can actually slow down the runtime by using spaces, now I have another reason not to use them.

  6. John says:

    Kind of an egotistical start, but nice article. PHP is a very high level language so little optimizations here and there won't make much of a difference and really depend on the developer's style and choice in coding like your little tip about string concatenation versus string separation in an echo statement.

    The variables $y and $z are never used so technically your answer is wrong that there is no comma separating them, because there should be no variables passing to the function.

    These tips won't get you a job. Certification and a degree get you a job. If you want to have a good job, and a long term one, then learn to love what you're doing and become good at it.

    Think twice about writing articles like this because it makes you sound like an ass, even though some of your tips are useful.

  7. Justice says:

    Neat, but it won't actually get you a job. Interviewers won't test you with these details, they'll rather want to see you be able to design and implement a proper object-oriented program, apply design patterns where needed, etc. Optimizations like using a comma between echo parameters are irrelevant if your program is inherently slow due to poor design, or if development time is twice the amount it would be if the author knew proper design and how to write re-usable code.

  8. blake says:

    Wow, lots of comments this morning. Looks like this article got hit by StumbleUpon. I'll try to address the comments in order.

    #1 varun: You're right, following the techniques in this article isn't going to magically speed up the performance of your app. On the other hand, knowing and using the most efficient coding practices is the point I was making with the article.

    #2 Frank: I don't think I contradicted myself there? I was explaining each line, from slowest to fastest. You are right, the last one is the fastest, and good point on the count.

    #3 Thanks Dwayne, I appreciate your comments. You're right about small apps, micro-tinkering can be time-consuming and the payoff might not be worth it. Small apps have a tendency to grow into big apps though, so if you've got your "best practices" in place before then, growth can be less painful.

    #4 Don, you're right about $y not being used. I noticed that too… it's not any kind of fatal PHP error, but if I saw something like that in some code, I'd be very suspicious and change it. Bad style. Come to think of it, if I took that quiz again, I'd probably mention that one too.

    #5 Andrew – excellent, another tab user! I think we'd have trouble proving any sort of noticeable slow-down on run-time for parsing the whitespace, but it's the theory that counts. In any event, a byte saved is a byte earned, so a tab vs. 4 spaces will also save you 3 bytes of disk space! How Scroogey is that?

    #6 John – Hmm, I didn't think I was being egotistical. Everything I relate above is true and stems from experience, not ego. You're right about $y and $z, but as I mentioned to Don, that's not a fatal error, and I didn't write the question. In terms of these tips not getting you a job, well, a combination of several of these tips got me my last job and a recent job offer, so I'll have to stick to my guns on that one. I'll also have to disagree with you about certification and a degrees… just having one will absolutely not get you a job in programming. There are thousands of people with degrees and certificates… you need something that sets you apart from everybody else, especially for senior positions.

    #7 Justice – you're right, to a point. Small companies generally won't have an in-depth hiring program. I've worked for both large and small companies, and no one has ever asked me to design and implement a proper OO system in order to get the job. Interviewers don't often have time for this. You're right that these optimizations are useless if your program is inherently flawed… these tips aren't going to turn a bad programmer into a good one! They're nice to have in your bag of tricks however, and if you can impress a job interviewer with your knowledge of the language, then you've done your job.

  9. DGM says:

    Worrying about single quotes and double quotes is pretty useless. If you started with single quotes, and then need to switch to double quotes, your development time probably used up more time than all the CPU cycles combined that would have been used by the parser.

  10. blake says:

    DGM – As I mentioned in an earlier comment, none of these tips will give your app a magic performance boost. However, I don't really see any sudden situations where a bunch of strings in your application are suddenly going to need to be switched from single to double-quoted. If you need to change one, do it as you come across it. If you need variables in your string, use double-quotes from the get-go.

    Besides, if you follow tip #1 and never inline your variables inside of strings, you'll likely never need to change the quoting of your strings anyway.

  11. Mochie says:

    Nice, you read the same IBM article as I did, now we can both pretend to be c programmers while using php. In reality, it really doesn't matter, a double quote here is not going to make or break your program, it will impress other php fanboi's, but it won't make a lick of difference in your end result. Calling count a billion times to make code more readable might not be such a bad idea.

    Think outside the box, don't just regurgitate a textbook.

  12. Toochie says:

    Oh yeah, and you suck.

  13. blake says:

    Wow, Mochie/Toochie, having a bad day? Next time I'll be sure to consult you before writing a blog post to make sure I'm "thinking outside the box" and not "regurgitating a text book".

    Thanks for wasting everyone's time with your comment though.

  14. Brian says:

    I found another error in the code. There's instead of . Deprecated tags are for the loss. :)

  15. Brian says:

    It broke my HTML. I meant to say that you used an old HTML 4.0 break tag instead of an xhtml 1.0 currently compliant tag.

  16. Noam says:

    Wow, people are so negative. Thanks for taking the time to post this.

  17. If you're a real PHP developer, you gotta read it.

  18. EllisGL says:

    I found something in your for loop example.
    for($i = 0; $i < $count; $i++) {
    should be:
    for($i = 0; $i < $count; ++$i) {

    Yes, it's a "micro" optimization, but it all the small things that really add up. =)

    @frank – you can unset the variable after the loop…

  19. Eklyptic says:

    Nice article. I especially appreciate the knowledge about strings/quotes. Its good stuff that is not immediately obvious no matter how long you have been programming.

    Oh yeah, and a shout-out to Mochie… I love people who are better than everyone else. They make me giggle.

  20. Adam says:

    Good stuff.

    I'm with you on the space-for-tabs-arseholes. I've been told that I write "Girl Code"; I get slightly aggravated with badly formatted code. I call it OCD Code myself.

  21. jon says:

    I like this article. Back in 1987 when I started programming in C on computers with between 128k and 512k of memory these optimizations were key. I believe that they also showed a developer that would take the time to properly design a larger scale program. (In my experience they almost always did.)

    With the advent of interpreted languages, fast processors and TONS of memory, I think the optimizations are less important but I would still hire the developer that thought of them over someone who didn't.

    I don't think degrees mean anything when you are looking for a great coder. Some of the best developers I ever met came out of high school with no formal education. Admittedly the others came from MIT. :-)

  22. Eric says:

    My age really shows when I see people talking about how it is a waste of time to write the most efficient code possible and it irritates me to no end.

    Good article! Not much of a PHP programmer myself but I agree with everything you have wrote.

  23. Mike says:

    Fantastic post, I could have used this if it had been posted 2 weeks ago (I blame you). I love your rant at the end. Screw meaningless standards!

  24. rubayeet says:

    Nice article Blake, it was quite fun to read. Although I think you missed an important PHP best practice: the use of '===' instead of '==' when testing for equality. I am sure you heard of this, why not make this best practice #11 in your article?

    Cheers.

  25. Soren says:

    I agree with the general points, but not the micro-optimization points you make. There has to be some special need for a micro-optimization expert, which shouldn't affect your general chances of getting a job or not.

    In your examples:

    2) Eventually the strings will be concatenated, the savings by choosing one approach over the other is marginal.

    5) I don't think I've ever seen anyone using regular expressions just because they can :) (some maybe because they just cut'n'paste, but not because they deliberately use preg_replace over other simpler approaches).

    That said, for simple regexps that express what you can do with str_replace/strtr, the performance penalty is also marginal here. str_replace/strtr the same.

    6) Array length calculation such as count($arr) is O(1) in all standard languages today (including PHP).

    Cheers,
    Soren

  26. You think these tips will land someone a job? If I got asked a question such as "Do you only use single quotes around strings?" on a job interview I'd stand up and leave, rubbish.

  27. Binny V A says:

    I cannot agree with the 'short tags are bad' idea. I like using the <?= ?> in my templates. It looks much better than <?php echo ""; ?>

  28. Bastian says:

    Nice Post. But i don't think that those tips should / would be crucial for getting a job. Of course, programming in PHP demands some tricky language juggling to avoid performance leaks. But those things are basic and should be known by every programmer applying as a PHP developer. Using a good IDE such as ZEND for Eclipse will support you in writing beautiful, high-performance code. And there are even more thinks to keep in mind:

    - avoid instanciating objects in loops unless you use __destruct + unset() to force PHP to keep you RAM clean.
    - avoid methods with high path complexity (a high number of acyclic execution paths through that method)
    - avoid methods with high Cyclomatic Complexity (high number of decision points in a method)
    - using ArrayObject for communication between objects is fine; for inner use (collecting values, caching, building models) its bad in performance and memory use – use basic array instead.
    - (and so on….)

    For your 6th point (avoiding functions within for statement) there is a nice form for those who really don't want to add this additional line of code:

    for ($i = 0, $n = count($aData); $i < $n; $i++) {…}

    However, some of the points that really should matter in job interviews for programmers are:
    - how good is she in solving abstract and concrete problems that are described in a non-tech style.
    - how good is she in communicating solutions and problems to non-tech persons.
    - how good is she in designing abstract architectures out of a problem description
    - how good is she in rather using and integrating existing solutions to solve a problem than re-inventing the wheel everytime a problem has to be solved.
    - how good is she in discussing a problem with other developers and finding a good solution together instead of fighting for her opinion about how to build that solution.

    there are many more. but i really think that those things are much more important then just knowing the basics and tricks of a language.

  29. EllisGL says:

    I didn't notice the "anti" space for indention comment in the article. I use spaces for the reason that spaces will alway appear correct in what ever editor you are using. I have seen some IDEs and text editors that treat tabs different in the amount of space they give.

    @rubayeet: '===' where possible is must in book.

    @Binny V A: Short tags don't jive with XML. <?xml…. The engine will try to parse it. Unless you want to escape it out or use concatenation, which ends up being a little ugly. Also short tags are gone from PHP 6.

  30. blake says:

    Great comments everyone, thanks for taking the time to leave them. I won't respond to all of them, I was gone all weekend, but it's nice to get back and see some discussion!

    Quick response to those commenting on whether or not these tips will get you a job. It's not the tips themselves that are crucial … it's using them to demonstrate your expertise with PHP. If you can show your potential employer good form and function with your code, and be able to explain what you're doing, and more importantly why, that's what's going to impress them and show them you're on top of your game. I probably should have written a longer conclusion, now that I see how it's being interpreted.

    EllisGL – good point on the short tags being gone from PHP 6, I forgot to mention that they had been deprecated!

  31. Jim says:

    Well technically the is not incorrect. It would only be incorrect if you assume you're serving xhtml. Both html and 4.01 and xhtml 1.0 are active standards to correct Brian in his post above.

  32. Jim says:

    the <br> is not inccorect I mean.

  33. Sid Khullar says:

    @john: i think the wise-ass tone of your comment makes *you* sound like an ass. sorry.

    btw: certifications and degrees are b******t. they only get you jobs. doing what you like and being good at it, ensures you keep your job.

    sid

  34. Jach says:

    Nice article, I agree with some of it. (Really I stay away from micro-optimizations in a high-level language and focus on readability and quick development time.)

    I got a PHP quiz similar to that one for the last job I applied for. I noted the crucial errors, then I went off on a huge thing about the style of it. But what I would rather see is some quizzes that test the applicant's security knowledge. Read the news lately, you'll see there are tons and tons of sites (even 'quality' sites like the US Department of Homeland Security) that are being 'hacked' by simple SQL Injection attacks. (Thank God register_globals are turned off by default now, and if I recall correctly are completely removed in PHP 6.) Maybe something like this (possibly bad example, coming up with it on spur of the moment):

    In regards to security, first, use mysqli, second it's not hard to do a mysqli_real_escape_string() call or make your own custom escape_data() function that addresses the possibility of magic quotes. Here's the one I typically use:

    function escape_data($data) {
    global $dbc;

    if (ini_get('magic_quotes_gpc')) {
    $data = stripslashes($data);
    }

    return mysqli_real_escape_string($dbc, trim($data));
    }

    For some things I like to use htmlspecialchars() or htmlentities().

    All in all nice blog post. I really like how you urge using quotes around array keys. Also to note a friend of mine got into a temporary habit of using strings as functions ($b = 'blah'; $b('stuff');), which I snapped him out of. Just because a language allows something doesn't mean it should be done.

  35. blake says:

    Jach – I agree wholeheartedly. Big name web products continue to be poorly designed from the ground up. Just look at all the kerfuffle with the latest versions of Wordpress! The sad fact is that most managers are not concerned with security at all. There's too much of a "just make it work as fast as possible" mentality and security gets put aside as an afterthought. As a result, a lot of programmers don't even take security into consideration, when it should really be a fundamental part of the design process.

    A good framework can help ensure some of the basics, such as always escaping database data and htmlspecialchars. It's easier and more efficient to get into the habit of doing something like $obj->insert(), and have the database wrapper class always handle data escaping for you, or $template->show() and having the template classes always htmlspecialchars() where needed.

    I think overall, web development is slowly becoming more robust, but programming languages can never replace a programmer's knowledge, and it is imperative that people learn about security.

  36. Allison says:

    @Jach: Using prepared statements with mysqli help protect against sql injection and it's what I have started using. Not sure what kind of performance issues or anything, but I'd rather have my data protected from people.

    Good article :)

  37. belteshazzar says:

    interesting article, i'm kind of new to php and found the optimisation discussion really interesting.

    one this i thought tho is that "new Array()" isn't actually necessarily an error. there may be a class Array. but then of course the rest is assuming the use of array().

    i'd also include the lack of comments describing what the function does and its intended usage as an error.

  38. Chase says:

    I wanted to say that I agree its not so much about making the micro-optimizations to speed up the code, its about getting in the habit of using good coding practices.

    When I first got my current job I was being trained by the person that wrote the majority of the webapp that I would be working on (he was leaving the company but still sticking around for training and stuff). There was one screen where we color code records based on urgency. The way he had written the code, is as follows (pseudo codeish, 1 represents least urgent, 5 most urgent))

    $color = "";
    $color = $check_color_1();
    $color = $check_color_2();
    $color = $check_color_3();
    $color = $check_color_4();
    $color = $check_color_5();

    I made a big deal out of the fact that he has built that in a really stupid way. He should have started with the most urgent, and once he found a color, stopped. Given the size of the app at the time and simplicity of the functions, the performance didn't really suffer from how he did it, but it just annoyed the heck out of me because it was such a bad design.

    If we can get into the habit of doing the small things like
    echo 'foo',$bar instead of echo "foo $bar" (something I'm not in the habit of doing I must say. I still haven't broke the habit of using double quotes for a string without any variables) we teach ourselves to pay attention to the little things, and then the big things follow right behind.

    —–

    Another note on initializing variables, and this goes along with my habits thing. If you are in the habit of always initializing variables, then you are less likely to forget to do it when it does need to be done.

    One time at work we had decided it would be a good idea to email all of our customers a report of any unpaid invoices. The script was pretty simple. It would loop through an array of customers, and for each customer tt would loop through and build an array of all the unpaid invoices, then build a nice email with that data. However, I forgot to re-initialize the invoices array on each iteration of customers loop:

    foreach($customers as $customer){
    foreach($customer['invoices'] as $invoice){
    $invoices[] = $invoice;
    }
    }

    or something to that effect. Well, customer 1 got their invoice information. Customer 2 got theirs as well as customers 1's. Customer 3 got theirs as well as customer 1 and customer 2's, etc, etc.

    At some point the data got to large or something and the emails failed to send, but we still sent confidential information to people that shouldn't have seen it. I am very fortunate to have not lost my job over that one.

    —–

    A few other things and questions:

    loops:
    Another habit I am trying to break is always using foreach loops. You should use a for loop over a foreach loop when its not an associative array. There is actually a third way to iterate thats even better, but I forget what it is.

    Performance questions:
    Do you happen to know the impact of any of the following:

    $x[] = $y;
    versus
    $x[count($x)] = $y;

  39. Danltn says:

    Chase, perhaps you're thinking of

    reset($array);
    while(list($name, $value) = each($array))
    {
    /* Do something */
    }

  40. [...] a good programmer. This is specifically for PHP but could apply elsewhere for a lot of the tips.read more | digg [...]

  41. jonathan says:

    Thanks for this article! I'm a college student with an internship where I do some programming but not much. I've never been taught what techniques optimize code, and it's really nice to see these. Thanks again for sharing!

  42. blake says:

    Thanks for the comments everyone. belteshazzar, you're right, if there was an Array class then "new Array()" would be correct.

    Nice anecdotes Chase. I agree 100%… if everyone trained themselves on the little details there'd be less mistakes. As to $x[] = $y vs. $x[count($x)] = $y, I'm guessing the former is faster. In fact, I just found a note on the manual page for array_push() which states:

    Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.

    If $x[] is faster than array_push(), I'd extend that to guess that not having the count() function in there would simply make it faster too, but the only sure way would be to write a script to test it.

    Thanks for taking the time to leave a comment jonathan, I appreciate it!

    I'll try to answer comments faster too… I was gone all weekend again.

    blake

  43. Will says:

    Wow, I can't believe I actually read all of those comments haha. Well, I agree with everything you said. Very well done.

    Only thing I missed was the comma between $y and $z btw.

  44. blake says:

    Thanks Will!

  45. The one we use at work is SeasonTest, which really works well to split out the good from the bad.

  46. putik! says:

    nice article blake.. this tips will help me get started with PHP.. bookmarked!

  47. fatjoez says:

    so if i do <?php instead of <?

    i'll get a job

    lol

  48. Excellent article! I've been optimizing some code that runs our site for the past few months so all the tips I can get the better, especially as we look to move everything onto our own hardware.

  49. anemos says:

    I like the article, thanks. It's good that some people care enough to help others, and these kinds of posts always start up follow-up discussions which are even better.

    I've got two things to point out though:

    Using single quotes versus double quotes has no real-word difference, just check out http://phpbench.com and you might come to the same conclusion. I like to code using only double quotes, keeps my code consistent, most of the time, according to phpbench anyway, double quotes are faster than single quotes, especially on pure strings.
    Even though phpbench is a good resource, think for your self, after all, you are not in control of either hardware or software, so results aren't 100% trustworthy.

    And as belteshazzar mentioned, new Array() might not be wrong if there's a class called Array? Well frankly, I can't believe you're agreeing with him blake. array() can never be declared as either function or class, and that's not going to change in the near future either.

    All in all I thank you for the wonderful article, I myself am a php coder and my coding style changes all the time, I'm still in the process of finding the holy grail of coding style (I admit to being a perfectionist). This is why I appreciate it a lot when people share their experiences.

  50. blake says:

    Ah-ha! Kudos to you, anemos. You are, of course, absolutely right. You can't make a class named Array. Anyone trying that would quickly get a syntax error. Nice catch.

    That SeasonTest link that Daniel posted above is kind of interesting too… looks like a good exercise. I'll have to give it a shot.

Leave a Reply