Henry Lynx Henry Lynx - 15 days ago 9
PHP Question

String to int cast in php

Ok I just stumbled upon a strange behavior in PHP while trying to

validate if the user input is an integer.

When I try to cast a string

12345A
to int e.g

$int_var = (int)'12345A';


I get 12345.

Why isn't PHP throwing an exception, but silently omits the 'A'?

Answer

PHP tries to convert the initial part of the string to integer type:

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero).

The type casting feature is not supposed to throw exceptions, or fail in any other way, if the variable being cast is scalar. It will trigger a notice, if the variable is an object, but the conversion will be performed, nevertheless.

If you want to check, if $t variable contains a numeric value, use is_numeric:

if (is_numeric($t)) {
  // ...
}

Don't use is_int, since if $t is a string like '1234' (which is usually the case), then is_int will return false, because the type is string, but not int.

Also, consider trimming $t before the checks:

$t = trim($t);

since the user may submit something like " 123". But the application usually should not fail just because of the leading space.