Although most numbers in PHP are entered in using decimal (base 10), you may also specify them in hexadecimal (base 16) or octal (base 8). Of the two, the first is rare, and the second is even rarer, but it is important that you are aware of both in case you stumble across it one day.
As you know already, decimal numbers are specified using the digits 0 to 9, which makes 3291 the number three thousand two hundred and ninety-one. That same number in base 8, which uses just the digits 0 to 7, is 6333. In hexadecimal, which uses 0 to 9 then A, B, C, D, E, and F, the number is "CDB". However, if you specify the number in code like this, it will not work as expected:
$octalnum = 6333;
The reason for this is because PHP will read it as decimal 6333, which is actually octal 14,275! To specify that a number is written in octal as opposed to decimal, you must precede it with a 0. So, to say that you mean $octalnum to be set to octal 6333 (decimal 3291), you would use this code:
<?php $octalnum = 06333; print $octalnum; ?>
That script outputs 3291, as PHP always works with decimal internally, and converts octal 06333 to decimal 3291 when $octalnum is set.
To specify you are providing a number in hexadecimal, you need to precede it with 0x. For example, to use the number 68, you would use this:
<?php $hexnum = 0x44; print $hexnum; ?>
Again, note that the value is printed out in standard decimal. Octal notation is very rarely used in PHP. If you are on Unix, you may have to use it to specify permissions, but that's generally the only use. Hexadecimal notation ("hex") is more common, mostly because many hashing algorithms return text using hexadecimal characters, and also because HTML's colour codes are written in hex.
Next chapter: Variable scope >>
Previous chapter: Forcing a type with type casting
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.