inconsistency in converting string to integer, when string is hex, prefixed with '0x'

前端 未结 3 437
轻奢々
轻奢々 2021-01-14 05:44

Using PHP 5.3.5. Not sure how this works on other versions.

I\'m confused about using strings that hold numbers, e.g., \'0x4B0\' or \'1.2e3\'

3条回答
  •  情话喂你
    2021-01-14 06:14

    Is there (or, rather, should there be) any relation between is_numeric() and the way how PHP treats strings when they are used as numbers?

    There is no datatype called numeric in PHP, the is_numeric() function is more of a test for something that can be interpreted as number by PHP.

    As far as such number interpreting is concerned, adding a + in front of the value will actually make PHP to convert it into a number:

    $int = +'0x4B0';
    $float = +'1.2e3';
    

    You find this explained in the manual for string, look for the section String conversion to numbers.

    As it's triggered by an operator, I don't see any need why there should be a function in PHP that does the same. That would be superfluous.


    Internally PHP uses a function called zendi_convert_scalar_to_number for the add operator (assumable +) that will make use of is_numeric_string to obtain the number.

    The exact same function is called internally by is_numeric() when used with strings.

    So to trigger the native conversion function, I would just use the + operator. This will ensure that you'll get back the numeric pseudo-type (int or float).

    Ref: /Zend/zend_operators.c; /ext/standard/type.c

提交回复
热议问题