Decimal to Octal Converter in PHP

Converting a decimal number to an octal number is a common task in programming.

Below are the approaches to convert a number from decimal to octal in PHP:

Table of Content

  • Using PHP’s Built-in Functions
  • Using Manual Conversion

Using PHP’s Built-in Functions

In this approach, we are using PHP’s built-in function decoct() to directly convert a decimal number to its octal representation. The decoct() function takes a decimal number as input and returns its octal equivalent.

Example: This example shows the conversion of Decimal to octal using built-in functions.

PHP
<?php
$decimalNumber = 35;
$octalNumber = decoct($decimalNumber);
echo "Decimal Number: $decimalNumber\n";
echo "Octal Number: $octalNumber\n";
?>

Output

Decimal Number: 35
Octal Number: 43

Using Manual Conversion

In this approach, we are using manual conversion to convert a decimal number to octal in PHP. The function decimalToOctal takes the decimal number as input and iteratively calculates the remainder of division by 8, storing each remainder in a stack. It then retrieves the remainders from the stack in reverse order to build the octal number, providing the conversion result.

Example: This example shows the conversion of Decimal to octal using custom functions.

PHP
<?php
$decimal_number = 35;
function decimalToOctal($decimal_number)
{
    $octal_number = '';
    $remainder_stack = [];
    while ($decimal_number > 0) {
        $remainder = $decimal_number % 8;
        array_push($remainder_stack, $remainder);
        $decimal_number = intval($decimal_number / 8);
    }
    while (!empty($remainder_stack)) {
        $octal_number .= array_pop($remainder_stack);
    }
    return $octal_number;
}
$octal_number = decimalToOctal($decimal_number);
echo "Decimal Number: $decimal_number\n";
echo "Octal Number: $octal_number\n";
?>

Output

Decimal Number: 35
Octal Number: 43