Search code examples
phpcasting

String to Int shall throw instead of returning 0


If I cast a string with intval('string') or with (int) 'string' and if that string contains letters other than numbers I get int 0 as result.

Is there a way in which an catchable Exception is thrown, due to which I can check that the conversion was successful, so that the user can't accidentally enter 1O instead of 10?

Also is there a way to check for float?


Solution

  • Using preg_match("/\D/", 'string') would work for this. This function looks for a certain pattern in a string and returns true if it finds the pattern and false if it doesn't.

    The delimiter \D checks for non-digits, such as 0 and the forward slashes are for opening and closing the delimiter section.

    So, as it will return true when it find a non-digit value, you'll have to throw an error or return early from your program when this returns true. When it's false, everything is fine