Intval doesnot accept zero

Hi

I am using intval to validate the phone number so that user enters only numbers.

$contact_number=intval(trim($_POST['contact_number']));

The customer enters number as 0124587 and in the database “0” gets deleted.

only 124587 gets saved in the database.

how can i make “intval()” to accept “0”.

thanks
vineet

It’s a leading zero, so most numeric functions would drop it because it’s not significant when processing that string as a number. I think you’d need to use some other method of making sure the user only enters digits in the phone number, either loop through it and extract anything that doesn’t match, or there’s probably a regular expression if you can get your head around the syntax.

You can’t because intval’s output is a number and numbers don’t have leading zeroes because they are irrelevant. Simply don’t use intval() and keep the number as string. You can validate digits in your string with preg_match() or ctype_digit().

1 Like

hi lemon_juice

i tried ctype_digit() and it is working fine now

thanks
vineet

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.