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

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

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.