I’ve commented on this many times in the past across a number of forums and blogs. If you use as little PHP as possible to get something done, it is usually far easier to keep track of, both for yourself and for future readers of your code. Here’s a typical example, taken from the osCommerce forum;
Does anyone know how to show credit card numbers seperated by dashes like on admin/orders.php thanks in advance for the help
What this guy wants is a credit card number to be written like this: 4111-1111-1111-1111 instead of 4111111111111111 – quite why he wants it is beside the point as he should not be storing the info anyway in my opinion, but anyway, that doesn’t really matter as the point of this article is not about the legalities of storing CC numbers, but more about writing code nicely…
No-one replied to his thread, so he came up with a workable solution himself;
echo $cc_p1 . ‘-‘ . $cc_p2 . ‘-‘ . $cc_p3 . ‘-‘ . $cc_p4;[/php]
Here he is splitting the $order->info[‘cc_number’] into 4’s and adding a – between each. Easy enough. But look at the ugly code!
My solution is like this:
[php]echo rtrim(chunk_split($order->info[‘cc_number’], 4 , “-“), “-“);[/php]
Here I am using chunk_split to split the $order->info[‘cc_number’] into 4’s and adding a – at the same time after (not between) each block of 4. The only problem is that this will add a – onto the end of the number – to combat this I am using rtrim to take off the end – : so I go from this 411111111111111 to this: 4111-1111-1111-1111- to this: 4111-1111-1111-1111
Easy as 123? Well maybe not if you are not that skilled in PHP 😉
Of course, I am not saying that my way is the right way – there are probably many ways in which the same effect can be achieved. What you have to agree with is that my line of code is much sexier than the first block of code posted and much easier to read!
Have fun with PHP and osCommerce! You can click the links in the PHP snippets above to learn more about rtrim, chunk_split etc