PHP octdec() function


The octdec() function in PHP is used to convert an octal (base 8) number into its decimal (base 10) representation. This function is particularly useful in applications that involve octal numbers, such as file permissions in Unix-like operating systems.

Syntax:

octdec(string $octal_string): int
  • $octal_string: A string containing the octal number to be converted. The string should consist only of octal digits (0 to 7).
  • Return Value: Returns the decimal representation of the given octal number as an integer.

Example 1: Basic Usage

<?php echo octdec('10'); ?>

Output:

8

Explanation: The octal number 10 is converted to its decimal equivalent, which is 8 (1 * 8^1 + 0 * 8^0 = 8).

Example 2: Conversion of Larger Octal Numbers

<?php echo octdec('17'); ?>

Output:

15

Explanation: The octal number 17 is represented in decimal as 15 (1 * 8^1 + 7 * 8^0 = 8 + 7 = 15).

Example 3: Octal with Leading Zeros

<?php echo octdec('00020'); ?>

Output:

16

Explanation: Leading zeros do not affect the conversion; thus, 00020 is also converted to 16.

Example 4: Invalid Octal String

<?php echo octdec('18'); ?>

Output:

Warning: octdec(): Illegal octal string

Explanation: If the input string contains digits that are not valid in octal notation (like 8), PHP will issue a warning and treat the input as invalid.

Example 5: Zero

<?php echo octdec('0'); ?>

Output:

0

Explanation: The octal representation of 0 is simply 0.

Key Points:

  • Input Type: The input for octdec() should be a string containing only valid octal digits. If the string contains invalid characters, a warning will be generated.
  • Use Cases: This function is useful in various scenarios, especially in Unix/Linux environments, where file permissions are often expressed in octal format.

Example of Practical Use:

<?php $filePermissions = '755'; // Common permission setting in octal $decimalPermissions = octdec($filePermissions); echo "The decimal representation of file permissions $filePermissions is: $decimalPermissions\n"; // Example of using in a loop for ($i = 0; $i <= 10; $i++) { echo "Octal: $i => Decimal: " . octdec(decoct($i)) . "\n"; // Using decoct for demonstration } ?>

Output:

The decimal representation of file permissions 755 is: 493 Octal: 0 => Decimal: 0 Octal: 1 => Decimal: 1 Octal: 2 => Decimal: 2 Octal: 3 => Decimal: 3 Octal: 4 => Decimal: 4 Octal: 5 => Decimal: 5 Octal: 6 => Decimal: 6 Octal: 7 => Decimal: 7 Octal: 8 => Decimal: 8 Octal: 9 => Decimal: 9 Octal: 10 => Decimal: 10

Explanation: This example demonstrates how to convert an octal number to its decimal representation and shows how octdec() can be used in a loop to display decimal equivalents for numbers from 0 to 10.

In summary, octdec() is a useful PHP function for converting octal numbers into decimal format, making it essential for applications that involve octal number systems, such as file permissions in Unix-like operating systems.