convert a number from base 10 to base 2 in php

To convert a number from base 10 to base 2 in PHP, you can use the decbin() function which converts a decimal number to binary.

Here's an example code snippet:

main.php
$num = 27;
$binary = decbin($num);
echo $binary; // Output: 11011
66 chars
4 lines

In the code above, we first define a variable $num which holds the decimal number we want to convert to binary. We then use the decbin() function to convert $num to binary and store the result in a variable called $binary. Finally, we print the binary number using echo.

You can also define a function to convert any decimal number to binary:

main.php
function decimalToBinary($num) {
    return decbin($num);
}

echo decimalToBinary(27); // Output: 11011
104 chars
6 lines

gistlibby LogSnag