Horje
Octal to Decimal Converter in PHP

Given an octal number as input, we need to write a program in PHP to convert the given octal number into an equivalent decimal number.

Below are the approaches to performing octal to decimal conversion in PHP.

Using the octdec() function

In this approach, we are using PHP’s built-in octdec() function to convert octal numbers to decimal. This function takes an octal input as a string and returns its decimal equivalent. The example demonstrates how to use octdec() with different octal inputs, showcasing the conversion process.

Syntax:

octdec(value)

Example: The below example uses octdec() function to perform Octal to Decimal conversion in PHP.

PHP
<?php
$input = "67";
$decimal = octdec($input);
echo "Octal $input is Decimal $decimal\n";
$input = "512";
$decimal = octdec($input);
echo "Octal $input is Decimal $decimal\n";
$input = "123";
$decimal = octdec($input);
echo "Octal $input is Decimal $decimal\n";
?>

Output:

Octal 67 is Decimal 55
Octal 512 is Decimal 330
Octal 123 is Decimal 83

Using Manual Conversion

In this approach, we are manually converting octal numbers to decimal by iterating through each digit in the octal number, multiplying it by the corresponding power of 8, and accumulating the results to obtain the decimal value.

Example: The below example uses Manual Conversion to perform Octal to Decimal conversion in PHP.

PHP
<?php
$input = "67";
$decimal = 0;
$length = strlen($input);
for ($i = 0; $i < $length; $i++) {
    $decimal += intval($input[$i]) 
      * pow(8, $length - $i - 1);
}
echo "Octal $input is Decimal $decimal\n";
$input = "512";
$decimal = 0;
$length = strlen($input);
for ($i = 0; $i < $length; $i++) {
    $decimal += intval($input[$i]) 
      * pow(8, $length - $i - 1);
}
echo "Octal $input is Decimal $decimal\n";
$input = "123";
$decimal = 0;
$length = strlen($input);
for ($i = 0; $i < $length; $i++) {
    $decimal += intval($input[$i]) 
      * pow(8, $length - $i - 1);
}
echo "Octal $input is Decimal $decimal\n";
?>

Output:

Octal 67 is Decimal 55
Octal 512 is Decimal 330
Octal 123 is Decimal 83



Reffered: https://www.geeksforgeeks.org


PHP

Related
PHP Program to Find Area and Perimeter of Circle PHP Program to Find Area and Perimeter of Circle
PHP Program To Find Mean and Median of an Unsorted Array PHP Program To Find Mean and Median of an Unsorted Array
Binary to Octal Converter in PHP Binary to Octal Converter in PHP
How to Filter a Collection in Laravel? How to Filter a Collection in Laravel?
PHP Program to Convert a Given Number to Words PHP Program to Convert a Given Number to Words

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12