Cleaning Up Your Code – A Developer’s PHP Tip
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?
1 2 3 4 5 6 7 8 |
//$list = array('red', 'yellow', 'pink', 'blue'); $o = ''; foreach($list as $item) { $o .= $item.', '; } $o = substr($o, 0, -2); echo $o; //Outputs: red, yellow, pink, blue |
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?
1 2 3 4 5 6 7 8 |
//$list = array('red', 'yellow', 'pink', 'blue'); $o = ''; foreach($list as $item) { $o .= $item.', '; } $o = rtrim($o, ', '); echo $o; //Outputs: red, yellow, pink, blue |
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
.
1 2 3 |
//$list = array('red', 'yellow', 'pink', 'blue'); echo implode($list, ', '); //Outputs: red, yellow, pink, blue |
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
Randy
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.
Paul Robinson
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. 😉