9 Things I Wish I’d Known about PHP Years Ago

I have been working with PHP for a good number of years now – (not including WordPress development, does that count? 😉 ). Here are some of the things I wish I’d known at the very beginning. Most of them are small little code snippets but there are also a few points about diving into the code too deep. Towards the end are a few helpful resources which have helped me out along the way.


1. Array Manipulation#

Since the release to PHP 5.4 it has been possible to use square brackets when working with arrays e.g. var $x = [];. This was great because it was short and concise and required less thinking time for the developer. I did, however, find myself still using many of the original methods like array_push(). What I did not realise is that much of what you could do, you can still do with the newer syntax.

Array Push:

$array = [1];
$array[] = 2;
// result: array(1, 2)

2. Working with URLs#

If you passed parameters around with URLs in PHP before now, it’s likely that, at some point, you have done something like this:

return $url."?result=".$result."&reason=".$reason;

Which is actually perfectly correct and it works. A neater way though would be to use the http_build_query() function, which takes in an array and does the string generation for you. That means that the above line can become:

return $url."?".http_build_query([
    'result' => $result,
    'reason' => $reason

If you are doing things the other way around, you can also use parse_url() to take a URL as a string and to break it down into it’s constituent parts.

3. Ternary Operators#

In programming we use if statements a lot – of course we do, that’s programming. There are times though that writing a whole if-else statement is too much. If there is both the if and the else and there’s a single statement in each it might be appropriate to use a ternary operator. Here’s a comparison:

if ($x === 1) {
    echo "X is 1";
else {
    echo "X is not 1";
echo ($x === 1 ? "X is 1" : "X is not 1");

As you can see this is much smaller and once you get used to ternary operators they are just as readable. They are formed of a statement to begin with, then a question mark before the code if the statement is true and finally a colon with the code if the statement is not true. When I was just starting to use ternary operators I did get the ‘?’ and the ‘:’ mixed up often enough.

4. Making a Comma Separated String#

Another task I would often do the long way around, for no reason other than ignorance, is creating a comma separated string. This is a common task in programming and can to tackled manually but it creates large indistinguishable code blocks which you often have to comment to say what they do, or move them to their own function. The solution is to use the implode function which just joins items in an array together along with any separator you choose. Imploding things is often used along with explode (which splits things apart).

$items = [1, 2, 3, 4];
$csv = "";
foreach ($items as $key => $item) {
    $csv .= $item;
    if (key < count($items)-1) {
        $csv .= ",";
$items = [1, 2, 3, 4];
$csv = implode(",", $items);

Another helpful tip along these lines is if you wanted to remove any empty or incorrect array items so they are not apart of the csv. In the first empty above you would wrap everything within the foreach in its own if statement, checking $item is not empty. To shorten this though, all we have to do is use the array_filter() function to strip out any items that equate to false.

5. Testing Performance#

If you have ever had to optimize a PHP script, the basic starting point is being able to know if you change something whether it has made a difference or not. PHP can print out the execution time of your script as it’s running (though unless you flush the cache, they’ll all print once the script has finished). Here’s how I measure execution time when optimizing:

echo "Time: " . round((microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"]), 5);

The microtime(true) will return a floating point number of the system’s time at that moment. We then subtract the time when the script started with REQUEST_TIME_FLOAT. When outputting this, we round the number to five decimal places, just to be tidy - it’s not needed though.

Code Style & Power Mad Troubles#

6. PSR Standards#

When I first started using PHP I didn’t know about the PSR standards (the shame!). Developed by the PHP Framework Interoperability Group they are a method of standardizing common tasks in PHP. Before these existed people used their own styles so you’d have to switch if you worked on multiple projects.

  • PSR-0 Autoloading Standard specifies the naming convention when autoloading classes.
  • PSR-1 & PSR-2 Coding Standard specifies the exact layout your code should be using.
  • etc.

If this is new to you, it is well worth getting acquainted with it early on. If you want to use it, but are struggling then your text editor or IDE will probably have a plugin to check your code and point out where it doesn’t meet the standard.

View on Github{.btn.btn-primary}

7. Overriding method and calls#

PHP gives you exceptional control over your application. It allows you to override methods, name things what you like and to structure your application however you like. This isn’t always a good thing. It’s good if you know what you’re doing.

The example I’m think of is one particular piece of functionality where I changed a classes’ parent class for a new class, where I simply specified a __callStatic() method. From here this then called the relevant methods in the child with call_user_func_array() if the method name matched a pattern. It worked, but it shouldn’t have been done that way. Just because you can, doesn’t mean you should.

This is definitely an argument in favor of using a framework (like anyone needed more reasons!).

Learning & Tools#

This might turn into a bit of a link dump, but hopefully some of them will be new to you.

8. Resources#

  • /r/PHP - The subreddit for PHP is great to news and opinion (especially if you like comparing frameworks).

  • Phil Sturgeon’s Blog - A PHP-FIG member, always a good source of changes in the PHP community.

  • Sitepoint PHP - A well-maintained list of how to do things with PHP.

  • Laravel News - Up-to-date stream of Laravel/PHP news and tutorials.

  • Hacking with PHP - a big guide about everything (almost) in PHP.

9. Tools#

That’s all I can think of that the moment, but I’ll try and keep the list updated when I think of other things (I’m sure I’ve missed some obvious ones).

Hopefully you have liked this post, if you have any suggestions feel free to post them in the comments.

Photo by Caroline Granycome