decoct()
Today, we will discuss the decoct() function in PHP. This function is used to convert a decimal number to an octal number.
The decoct() function converts a decimal (base-10) integer into its octal (base-8) string representation. It is PHP's built-in tool for the decimal-to-octal direction of base conversion, the inverse of octdec().
Octal still shows up in real code — most notably in Unix file permissions, where 0755 and 0644 are octal values. decoct() lets you turn a computed permission integer back into the familiar three-digit string.
Syntax
decoct(int $num): string$num— the decimal integer to convert. If a float is passed, it is truncated to an integer first.- Return value — a string containing the octal representation. The result is a string, not a number, because octal values are typically displayed rather than used in further arithmetic.
The largest number that can be converted depends on the platform's integer size (PHP_INT_MAX). Negative numbers are interpreted using their two's-complement bit pattern for the platform's word size.
Basic example
Decimal 15 is 17 in octal (1 * 8 + 7 = 15). Note that echo prints 17 with no leading zero — decoct() never adds the 0 prefix that octal literals use in source code.
Common values
<?php
echo decoct(8); // 10
echo "\n";
echo decoct(64); // 100
echo "\n";
echo decoct(493); // 755 (the rwxr-xr-x permission set)
?>Because 493 in octal is 755, decoct() is handy when you read a numeric file mode and want to display it the way chmod expects.
Reading back a file's permission bits
fileperms() returns the mode including file-type bits, so mask with & 0777 to keep just the permission portion before converting:
<?php
$mode = 0755; // octal literal -> stored as decimal 493
echo decoct($mode & 0777); // 755
?>Gotchas
- Output is a string with no leading zero. If you need the conventional four-character form, prepend it yourself:
'0' . decoct(493)gives"0755". - Floats are truncated, not rounded.
decoct(15.9)returns"17"(same asdecoct(15)), because the float is cast tointfirst. - It only handles integers. For converting between arbitrary bases, use
base_convert()instead.
Related functions
octdec()— the inverse: octal string back to decimal.dechex()anddecbin()— convert decimal to hexadecimal and binary.base_convert()— convert a number between any two bases from 2 to 36.