Use hexdec() when you need to parses a hexadecimal number string into a PHP numeric value in a PHP application. The examples below show the actual operation and its limitations.
What Is hexdec() in PHP?
Parses a hexadecimal number string into a PHP numeric value. The exact signature supported by your installation depends on its PHP version and enabled extensions.
Its syntax is:
hexdec(string $hex_string): int|float
Parameters and return value: The parameter types, optional arguments, references, and return type are shown in the signature above. Optional parameters are marked with an ellipsis in this reference signature.
Example 1: Basic Usage
<?php
echo hexdec("FF");
Output:
255
Example 2: Different Input or Behavior
<?php
echo hexdec("10");
Output:
16
Practical Example: Applying the Function
<?php
$colors = ["0A","1F","7F"]; foreach ($colors as $hexValue) echo hexdec($hexValue) . PHP_EOL;
Output:
10
31
127
Important Behavior and Edge Cases
Large values may become floats, losing integer precision. Validate input before converting.
Comparison With Related Functions
| Approach | Difference |
|---|---|
hexdec() | Parses a hexadecimal number string into a PHP numeric value. |
| Related operation | dechex() converts an integer into hexadecimal text. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring the function-specific limitation | Large values may become floats, losing integer precision. Validate input before converting. |
| Confusing this function with a related operation | dechex() converts an integer into hexadecimal text. |
Key Takeaways
- Parses a hexadecimal number string into a PHP numeric value.
- Large values may become floats, losing integer precision. Validate input before converting.
- dechex() converts an integer into hexadecimal text.
Use hexdec() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.