PHP Tutorial - PHP Integer






Integers hold whole numbers, either positive or negative, such as 1, -20, 12345,etc. The limit of integer is between -2147483647 and 2147483647. The integer numbers outside the range are automatically converted to floats.

The following code adds two integer values together in PHP.


<?php 
$var1 = 5; 
$var2 = 2; 
$answer = $var1 + $var2; 
print "$var1 plus $var2 equals $answer."; 
?>

The code above generates the following result.





PHP integer Literal

We may specify integers in hexadecimal (base 16) or octal (base 8). The octal number system only uses the digits 0 to 7. hexadecimal uses 0 to 9, then A, B, C, D, E, and F.

To specify number in octal, we must precede it with a 0 (zero).


<?PHP
$octalnum = 06331; 
print $octalnum; 
?>

The code above generates the following result.





Hexadecimal

To specify a number in hexadecimal, precede it with 0x.


<?PHP
$hexnum = 0x44; 
print $hexnum; 
?>

The code above generates the following result.

Example - Integer literal

The following code uses different integer literals to assign value to integers.


<?PHP//from ww  w.j  av a 2s.c o m
$a = 1234; # decimal number
print($a);
print("\n");
$a = -123; # a negative number
print($a);
print("\n");
$a = 0123; # octal number (equivalent to 83 decimal)
print($a);
print("\n");
$a = 0x12; # hexadecimal number (equivalent to 18 decimal)
print($a);
print("\n");
?>

The code above generates the following result.

Float

Floats hold fractional numbers as well as very large integer numbers, such as 4.2, 1.00000001, and 123123123123000.

Floating-point numbers are called real numbers or just floats.

Float Literal

We may also specify an exponent with your float, i.e., 3.14159e4 is equal to 31415.9.


<?PHP
$a = 1.234; 
print ($a);
print ("\n");
$a = 1.2e3;
print ($a);
?>

The code above generates the following result.

Example - floating-point arithmetic

Here are some examples of floating-point arithmetic:


<?PHP//from   w  w  w .  ja  v a2  s.co  m
$a = 1.132324; 
print($a);
$b = $a + 1.9; 
print($b);
$b = $a + 1.0; 
print($b);
$c = 1.1e15; 
print($c);
$d = (0.1+0.7) * 10; 
print($d);
?>

The code above generates the following result.

Example - Calculate the area of a circle of given radius

Calculate the area of a circle of given radius


<?php//  w  w  w  . j a  va2s. co m

$radius = 2.0;
$pi = 3.14159;
$area = $pi * $radius * $radius;

echo("radius = ");
echo($radius);
echo("<BR>area = ");
echo($area);
?>

The code above generates the following result.