How to Convert a Hexadecimal String to an Integer in PHP?

PHP hexadecimal string to integer conversion

You can convert a hexadecimal string to an integer by using the hexdec() function, for example, like so:

var_dump(hexdec('4D2')); // int(12345)
var_dump(hexdec('04D2')); // int(12345)
var_dump(hexdec('0x4D2')); // int(12345)
var_dump(hexdec('0x04D2')); // int(12345)

This works for values prefixed with 0x, as well as values that don't have a prefix.

For invalid values passed to hexdec() (i.e. values beyond 0-9 and a-f), this would show a deprecation message in PHP 7.4+ (and silently ignored in versions prior):

// ...

// Deprecated: Invalid characters passed for attempted conversion, these have been ignored

Hope you found this post useful. It was published . Please show your love and support by sharing this post.