-3

I am storing U.S. phone numbers in MySql table as a bigInt(10).

Example: 1234567890

I want to convert that into a formatted phone number in either mysql or php

Example: 1234567890 => (123) 456-7890

Does anyone know how to accomplish this?

user2763616
  • 21
  • 1
  • 8
  • i think this is already answered here: using php http://stackoverflow.com/questions/4708248/formatting-phone-numbers-in-php – Kevin Jul 30 '14 at 04:27
  • possible duplicate of [How do you format a 10 digit string into a phone number?](http://stackoverflow.com/questions/2089923/how-do-you-format-a-10-digit-string-into-a-phone-number) – Mark Miller Jul 30 '14 at 04:28
  • or http://stackoverflow.com/questions/5872096/function-to-add-dashes-to-us-phone-number-in-php – Mark Miller Jul 30 '14 at 04:29

1 Answers1

0
<?php
function format_phone_number($number)
  $number_string = '('.substr($number, 0, 3).') ';
  $number_string .= substr($number, 3, 3).'-';
  $number_string .= substr($number, 6);
  return $number_string;
}
?>

Here, we use the substr function three times to grab small text substrings of the whole number string. Remember that upon using this function, PHP will automatically turn the number into a string, so you don't have to worry about calling a string function on a variable that is the number type. It appends the extra characters (, ), and - by using PHP's concatenation operator, the period. I split it up into three statements just for manageability, though you could perform this whole function in one long line if you'd like, as follows:

<?php
function format_phone_number($number)
  return '('.substr($number, 0, 3).') '.substr($number, 3, 3).'-'.substr($number, 6);
}
?>
elijahcarrel
  • 3,787
  • 4
  • 17
  • 21
  • I tried to use your code and names the $number as my variable value (the #) but I got no result biz_phone; function format_phone_number($number){ $number_string = '('.substr($number, 0, 3).') '; $number_string .= substr($number, 3, 3).'-'; $number_string .= substr($number, 6); return $number_string; } ?> – user2763616 Jul 30 '14 at 04:41
  • here is the solution that worked: biz_phone; // given $formatted = "(".substr($num,0,3).") ".substr($num,3,3)."-".substr($num,6); echo $formatted; ?> – user2763616 Jul 30 '14 at 04:50
  • To use a function in PHP, you must declare it as you have done, and then you have to call it at some point. For example, you would use the code `biz_phone; echo format_phone_number($num); function format_phone_number($number){ $number_string = '('.substr($number, 0, 3).') '; $number_string .= substr($number, 3, 3).'-'; $number_string .= substr($number, 6); return $number_string; } ?>` Sorry this wasn't clear. Glad to see you got it working without the use of a function. – elijahcarrel Aug 01 '14 at 03:19