Implied cast differs from explicit cast - Page 2

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

Re: Implied cast differs from explicit cast

Am 16.01.2012 02:10, schrieb lb:
Quoted text here. Click to load it

I think it is odd. The notion of "hex string" does not make sense of it.


Re: Implied cast differs from explicit cast

El 16/01/2012 2:10, lb escribió/wrote:
Quoted text here. Click to load it

Interesting subject... There are actually two different sections in the
PHP manual:


Explicit cast:

«To explicitly convert a value to integer, use either the (int) or
(integer) casts. [...] A value can also be converted to integer with the
intval() function.»

It admit it's not 100% clear but I have the impression that the
underlying code is just the same and intval():


Implicit cast:

«When a string is evaluated in a numeric context, the resulting value
and type are determined as follows.»

First difference is that you don't necessarily get an integer:

«If the string does not contain any of the characters '.', 'e', or 'E'
and the numeric value fits into integer type limits (as defined by
PHP_INT_MAX), the string will be evaluated as an integer. In all other
cases it will be evaluated as a float.»

Second difference is that a standard C library is mentioned:

«For more information on this conversion, see the Unix manual page for

... thus we can get further details:

«The expected form of the (initial portion of the) string is optional
leading white space as recognized by isspace(3), an optional plus ('+')
or minus sign ('-') and then either (i) a decimal number, or (ii) a
hexadecimal number, or (iii) an infinity, or (iv) a NAN (not-a-number).»


I believe the most relevant difference is that:

- intval() accepts any base but does not guess (defaults to 10)
- strtod() only accepts base 10 and 16 and does guess

... which explains your issue.

-- - Álvaro G. Vicario - Burgos, Spain
-- Mi sitio sobre programación web:
-- Mi web de humor satinado:

Re: Implied cast differs from explicit cast

Thanks to all who replied, more or less...

I was not trying to convert hex to decimal or any such thing. I was
cleaning up some code that looked something like this:

  if (is_numeric($data[$i])) {
      $val = (double)$data[$i++];
  } else {

I changed it to:
  if (is_numeric($val = $data[$i++])) {

During testing I found that I could get different results within the
block with $val used as a numeric value in calculations. The difference
was when a string containing a hex value was used in the data array.
This is odd behavior, and inconsistant, in my opinion, and might be
considered a PHP bug.

Site Timeline