Using PHP to format phone numbers

PHP is great. It complements JavaScript wonderfully. You may have already formatted the phone number on the front end, but what about on the backend? There comes a time when you need to use php to format a phone number. I use this function in my projects all the time.

PHP Format Phone Number Function

You might be wondering why I have 2 functions in there, right? Well, here’s the thing. I like to make things resusable. That being said, I’m leaving the door open to use the same kind of interface, format_phone(‘us’, $phone) or format_phone(‘canada’, $phone), to format other types of phone numbers should the functions exists. I’ll leave those types of implementations as homework.

What did we learn today?

We, well, mostly you since I wrote this right? You just learned how to “php format phone.” Use with caution, but use it. If you are an agency or you need another PHP developer by your side, please contact The Barton Organization today for php development work.

  1. Dave Shaffer Reply

    This was really useful!

    I ended up using this in OpenCart’s abstract controller class so it would be available to all templates. To make this work I changed a couple things:

    1. I changed the if(function_exists($function)) { line to if (method_exists($this, $function)) {
    2. I changed the method signature to function format_phone($phone, $country = 'us') { since that’s a useful default for my application

    Thanks!

  2. neotechni Reply

    ” Well, here’s the thing. I like to make things resusable. ”

    I love you. Far too many programmers don’t do that. Even the PHP example site doesn’t make their code reusable.

    BTW: I used the same 2 function approach for sending SMS messages (instead of country, it was the SMS service provider)

Leave a Reply