PHP Integers

PHP Integers

Theory About Character Values

Here a little theory about integers with PHP. Although, most applications use regular numbers like 1,2 and 3, you can use other coding means to represent numbers. Three methods shown below are hexadecimal, binary and octal notation. .

Hexadecimal

The hexadecimal format used the characters are ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"). The f is actually 15. Some sample hexadecimals are 0x0, 0x1 and 0x1B. The actual integer values of each of these hexadecimals are 0, 1 and 27. The 27 comes from the 1 which is 16 and b which is 11. To make this easy tp remember, you can remember to carry the number when it hits 16(which is F).

Binary Values

With binary numbers, all numbers are based on the exponential value of 2. Thus, a value like 11100 is (2 to the power of 4) + (2 to the power of 3) + (2 to the power of 2) + (0*(2 to the power of 1)) + (0(2 to the power of 0)) = 28.


Octal Notation

When you hear octal, you are probably thinking the number 8. Octal notation is based on a 1-8 system and has a zero as the first decimal. To make this more clear, a number like 07 is seven, while 017 is 15. In the latter case, you have one complete 8 plus 7 from the first column. By comparison, the number 0117 if 7 + 8(1) + 8(8) =  79.

Sample

The code below shows a binary number, hexadecimal number, octal number and a regular integer. Then, all the values are added up. As you can see, PHP will out an integer. To use a binary number, you need to add 0b in front of the binary value. The ob has been available since PHP 5.4.

 <?php 
$a = 0b00000110; // Binary Outputs 6 
$b = 0x1F; // Hexadecimal Outputs 31  
$c = 2; 
$d = 011; // Octal Outputs 9 
echo "a=$a b=$b c=$c d=$d<br/>";  
echo $a + $b + $c +$d; // Outputs 48 
?>

Browser Output

The output below is what you will see in your browser.

a=6 b=31 c=2 d=9
48