1

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

6
  • 2
    because the string has a 0 before it has any Non-Numeric (the x) which terminates the cast, or intval() as its not a numeric Commented Jan 4, 2022 at 17:25
  • If you can post an actual code sample with the literal string you're trying to convert we can probably give you a more useful answer than "well I guess don't do that". Commented Jan 4, 2022 at 17:27
  • If you want the decimal value of a hexadecimal string, use hexdec. But remove the "0x" first. Commented Jan 4, 2022 at 17:27
  • Simple test, run echo (int)"3x55"."\n"; and you will get 3 Commented Jan 4, 2022 at 17:27
  • Also see php.net/manual/en/… and php.net/manual/en/language.types.numeric-strings.php Commented Jan 4, 2022 at 17:31

1 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.