Skip to content
Advertisement

strange question about PHP convert string to int

im trying to convert string to integer but return 0 or wrong number. Below is the code i have tested. Anyone know why? Thanks

<?php
echo gettype(0x55)."n"; //type is integer
echo 0x55."n"; //this is correct
echo (int)"0x55"."n"; //why 0?
echo intval("0x55"); //why 0?

return

integer 85 0 0

Advertisement

Answer

By default, intval() parses base 10, so it ignores the 0x prefix.

If you specify the base as 0, it will determine the base dynamically from the string prefix: 0x means hex, 0 means octal.

So use intval("0x55", 0).

DEMO

I don’t think there’s any equivalent for the typecast syntax (int).

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement