base_convert
Converts a number from one base to another.
Syntax
base_convert(string $num, int $from_base, int $to_base): stringParameters
| Parameter | Type | Description |
|---|---|---|
| $num | string | The number as a string. |
| $from_base | int | The source base, from 2 to 36. |
| $to_base | int | The target base, from 2 to 36. |
Return value
stringThe number in the new base.
Examples
Decimal to binary and back:
<?php
echo base_convert('10', 10, 2), "\n";
echo base_convert('1010', 2, 10);Output:
1010
10A short code from a large number:
<?php
echo base_convert('123456789', 10, 36);Output:
21i3v9Notes
Common cases have functions of their own: decbin(), bindec(), dechex(), hexdec().
See also
Related recipes
In the tutorial
- Numbers and maths — PHP's maths functions — rounding, number formatting, random numbers and the precision of fractions.