How do `intval ()` and `(int)` handle whitespace characters?

PHP Manual Converting Strings to Numbers says:

The value is specified by the beginning of the string. If the string starts with valid numeric data, this will be the value to use. Otherwise, the value will be 0 (zero).

This means that anything but a number, plus or minus at the beginning of the string, should return 0

when the string is converted to a number. However, (some) spaces at the beginning of the line are ignored:

echo intval("     3");  // 3
echo intval("
3");  // 3

      

Are there any gaps that are intval()

and (int)

are not separated?

Where is this behavior specified?

+3


source to share


1 answer


The observed behavior is largely undocumented. Probably the space removal depends on strtod()

in C which one should use isspace()

.

intval()

manual
says:

The general integer casting rules apply .

After the link (links removed):

To explicitly convert a value to an integer, use either drives (int)

or (integer)

. However, in most cases, no cast is required because the value will be automatically converted if an integer argument is required for the structure of a statement, function, or control. The value can also be converted to an integer using a function intval()

.

So it looks like casting and are intval()

equivalent. And just below the quote above:



From strings

See Convert strings to numbers

OK. Nothing really useful to us other than this little note:

For more information on this conversion, see the Unix man page for strtod (3).

After the link flow, select the version strtod()

specified by POSIX
, the UNIX API standard again .

These functions should convert the initial part of the string pointed nptr

to to , and , respectively. First, they decompose the input string into three parts: 1. The original, possibly empty sequence of whitespace characters (as indicated ) ... double

float

long double

isspace()

Common sense tells us that this should only apply to floats because it strtod()

returns a floating point number in C, but number parsing and internal representation is freaky in PHP, as is pretty much everything in the language. Who knows how it works under the hood. Better not to know.

0


source







All Articles