The base_convert()
function in PHP is used to convert numbers between different bases, such as binary, decimal, octal, or hexadecimal.
It accepts the number as a string, the base it’s in, and the base to convert to (ranging from 2 to 36).
The output is always a string, regardless of base.
Common uses include data encoding, binary/hex manipulation, and unique ID generation.
Example: base_convert("255", 10, 16)
returns "ff"
.
Syntax
base_convert(string $number, int $from_base, int $to_base): string
- $number – The number you want to convert (as a string)
- $from_base – The base the number is currently in (2–36)
- $to_base – The base you want to convert to (2–36)
- Returns – The converted number as a string
File Name: base-convert-example.php
<?php
echo base_convert("15", 10, 2); // ➤ "1111" (Decimal to Binary)
echo "\n";
echo base_convert("1111", 2, 10); // ➤ "15" (Binary to Decimal)
echo "\n";
echo base_convert("255", 10, 16); // ➤ "ff" (Decimal to Hex)
echo "\n";
echo base_convert("ff", 16, 10); // ➤ "255" (Hex to Decimal)
?>
Real-World Use Cases
Use Case | Example |
---|---|
Binary ↔ Decimal | base_convert("1010", 2, 10) |
Decimal ↔ Hexadecimal | base_convert("255", 10, 16) |
Base36 Encodings | base_convert("123456", 10, 36) |
Custom ID generations | Convert long numbers to short strings |
Summary
Feature | Description |
---|---|
Function | base_convert() |
Use | Convert between number systems (bases) |
Input | Number as string, base from, base to |
Output | Converted number (string) |
Base Range | 2 to 36 |