Be a Better PHP Developer: The Basics

Main Thread August 7, 2012 • 2 min read

As a consultant I see a lot of code. I also dedicate a few hours per week to StackOverflow. Unfortunately a lot of the PHP code I see is a candidate for Jeremy Kendall‘s CSI: PHP. PHP has a bum rap as unsophisticated. But this isn't PHP's fault. It's the developers. Better code starts with you! Time to step up and be a better PHP developer.

I created an initial set of tips that will help you become a better PHP developer. While these can be abstracted to any language, my examples are specific to PHP. Furthermore, I have left out those I felt were personal preference – such as code formatting or avoiding PHP's alternative syntax.

Don't use PHP short tags

While I appreciate the shorthand, avoiding three additional keystrokes is the ultimate laziness. Especially when three keystrokes cost more than you realize – namely compatibility and portability.

Yes, short_open_tags is an INI setting. Yes, it was re-enabled by default in PHP 5.3. But not every server runs PHP 5.3. Not everyone can modify their INI. Using XML? How do you differentiate between an XML header?

PHP short tags can get messy and confusing. Use <?php. It's clear and says, “Hey bitches, I'm writing PHP!”.

Stop using the MySQL library

Please stop using mysql_* functions as they have not been updated in quite some time and are in the deprecation process. Use MySQLi or PDO.

If available, I recommend going straight to PDO. Do not pass MySQLi. Do not collect technical debt. However, read the docs for more details between choosing the API.

RTM: String and Array

I see a lot of code for parsing or manipulating strings and merging or sorting arrays. Often this code is custom written. If I had a nickel for every line of code to search a string with a regex or sorting a multidimensional array…

PHP has thousands of native functions. Over 100 of these are array functions and string functions. Take 15 minutes to click through each of these functions and read the function definition. You will find gems like strpos(), parse_str(), array_filter(), and array_reduce().

PHP has excellent documentation. Once you're done with String and Array, you should browse the other PHP functions.

Go forth and be a better PHP developer

I guarantee putting these tips into practice will put you on the path to becoming a better PHP developer. In the end, it's about knowing your language and staying current. On that note, you should jump over and read my post about Routines of a Good Developer.

This post is part of a series on How to be a Better PHP Developer.

Find this interesting? Let's continue the conversation on Twitter.