convert a number from base 2 to base 8 in php

To convert a number from base 2 (binary) to base 8 (octal) in PHP, you can use the base_convert() function.

This function takes three arguments: the number to be converted, the original base, and the target base.

main.php
<?php
$binary_number = "11010111";
$octal_number = base_convert($binary_number, 2, 8);
echo "Octal equivalent of binary number $binary_number is $octal_number";
?>
164 chars
6 lines

In the code above, we first define the binary number as a string. We then use the base_convert() function to convert this binary number to its octal equivalent. The second argument, 2, indicates that the original base is binary, and the third argument, 8, indicates that the target base is octal.

The output of the code above will be:

main.php
Octal equivalent of binary number 11010111 is 327
50 chars
2 lines

Note that the base_convert() function can also be used to convert numbers to and from other bases, such as hexadecimal (base 16).

gistlibby LogSnag