0

I have a input for user to enter phone number and I use int(); before I insert it into database.

I insert some phone number 0398765899->398765899 into DB

PHP int(); auto remove the first 0, it seems fine but I when I try

   $var=0177;
    echo $new=(int)$var;

in PHP file, the result become 127

user2178521
  • 833
  • 1
  • 14
  • 26

5 Answers5

4

A phone number is a string; not a number. Think 1-800-FOO-BANG.

Also, note they're not always formatted the same way. Examples:

  • (123) 456 7890 or 123-456-7890 -- US
  • (+33) 1 23 45 67 89 -- France
Denis de Bernardy
  • 75,850
  • 13
  • 131
  • 154
  • what if user tyep some text on top, like wa 098 ow 988 – user2178521 Jun 10 '13 at 12:27
  • to add on to that - check out http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation – ddavison Jun 10 '13 at 12:27
  • @user2178521: that's up to you to decide, much like it's up to you to decide which zip code formats are acceptable. (hint: there are dozens of zip code formats out there, and a few countries have no zip codes at all.) – Denis de Bernardy Jun 10 '13 at 12:30
1

Use php filters:

filter_var($var, FILTER_SANITIZE_NUMBER_INT);
maximkou
  • 5,252
  • 1
  • 20
  • 41
0

This doesn't work:

$var=0177;
echo $new=(int)$var;

Because PHP think this is an octal number. This works:

$var='0177';
echo $new=(int)$var;
Alexandre Danault
  • 8,602
  • 3
  • 30
  • 33
0

It's because a number in the format 0ddd is treated by PHP as an Octal number. That's why you get 127 after conversion to int.

also as @Denis suggests storing phone numbers as int is not a good idea.

Michal Trojanowski
  • 10,641
  • 2
  • 22
  • 41
0

when you convert the value to integer it will remove the first zeros always,because zero has no significance at first place according to significant digits. you have to leave the number as a string.

Shahbaz
  • 3,433
  • 1
  • 26
  • 43