Cleaning Up Your Code – A Developer’s PHP Tip

/ PHP / by Paul Robinson / 2 Comments
This post was published back on June 7, 2013 and may be outdated. Please use caution when following older tutorials or using older code. After reading be sure to check for newer procedures or updates to code.

Today I thought I’d give you one of my famous developers tips. All right, so they aren’t famous. Yet!

I’m sure, if you are a PHP developer, you have created a loop many a time. They are useful for all sorts of things, including creating lists. Let’s take a common one. Creating a comma separated list. Does this look familiar?

I’ve seen this a huge amount of times, and while it isn’t the prettiest of code, there isn’t anything ‘wrong’ with it. However, how can we make it cleaner? Well how about this as an alternative?

Not a lot cleaner, but much easier to understand as we can see what rtrim is removing. That is opposed to having to understand that substr was reverse trimming the string of it’s last 2 characters.

Can we make this even cleaner though? Well yes. The astute among you may have already noted that PHP has a pre-made function that will create your comma separated list in a heartbeat. What is this magical function? Well, it’s explode‘s (arguably) lesser known sister implode.

The Point

You may be wondering what this tutorial is about. Well it’s to give newer developers a little tip, and to show that some code is cleaner & more efficient than others. That’s not to say the first two examples should never be used (although the second is much better), there is nothing wrong with the first two examples, the third is cleaner and easier to understand (and more efficient).

That’s all folks. Do you have any PHP tips or snippets that you use all the time? Why not share them with us in the comments and, with your permissions, I might make a post on it for you.

2 Comments

Author’s gravatar

The one snippet I always keep handy is for truncating a string but making sure a full word is not sliced up such as a character count might do.

Reply
Author’s gravatar author

Hi Randy,

Thanks for sharing. That is a very handy snippet, especially for WordPress developers who use it quite a lot for creating makeshift excerpts.

My favourite version was always this one as you can enter how many words you’d like it limited to. It’s deceptively simple too;

I made it for using in WordPress themes I create for clients, but I’m sure it would be handy elsewhere too. 😉

Older Comments
Newer Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

I'll keep your WordPress site up-to-date and working to its best.

Find out more