PHP Numbers Explained
Numbers are one of the most frequently used data types in PHP. Whether you’re calculating product prices, applying discounts, processing payments, generating invoices, or displaying statistics, you’ll work with numbers.
PHP supports different numeric data types and provides many built-in mathematical functions that simplify calculations.
In this tutorial, you’ll learn how PHP handles numbers and how to use them effectively in real-world projects.
What are Numbers in PHP?
PHP mainly supports two numeric types:
- Integer (int) β Whole numbers
- Float (double) β Decimal numbers
Examples:
<?php
$age = 28;
$price = 999.99;
echo $age;
echo "<br>";
echo $price;
?>
Output
28
999.99
Integer Numbers
Integers are whole numbers without decimal points.
Example:
<?php
$students = 250;
echo $students;
?>
Examples of integers:
- 10
- 100
- -45
- 5000
Floating Point Numbers
A float (or double) contains decimal values.
Example:
<?php
$discount = 12.5;
echo $discount;
?>
Output
12.5
Floats are commonly used for:
- Product prices
- GST calculations
- Percentages
- Ratings
- Currency values
Checking Number Types
PHP provides built-in functions to identify numeric types.
is_int()
<?php
$number = 50;
var_dump(is_int($number));
?>
Output
bool(true)
is_float()
<?php
$value = 99.95;
var_dump(is_float($value));
?>
Output
bool(true)
is_numeric()
Checks whether a value is numeric.
<?php
$value = "150";
var_dump(is_numeric($value));
?>
Output
bool(true)
This function is useful when validating user input from forms.
Basic Mathematical Operations
PHP supports all common mathematical operators.
<?php
$a = 20;
$b = 5;
echo $a + $b;
echo "<br>";
echo $a - $b;
echo "<br>";
echo $a * $b;
echo "<br>";
echo $a / $b;
?>
Common Math Functions
Absolute Value
echo abs(-100);
Output:
100
Square Root
echo sqrt(64);
Output:
8
Random Number
echo rand(1,100);
Generates a random number between 1 and 100.
Maximum Number
echo max(10,55,90,12);
Output
90
Minimum Number
echo min(10,55,90,12);
Output
10
Real-World Example
Calculating a product discount.
<?php
$price = 1500;
$discount = 20;
$finalPrice = $price - ($price * $discount / 100);
echo "Final Price: βΉ" . $finalPrice;
?>
Output
Final Price: βΉ1200
This type of calculation is widely used in e-commerce websites, billing software, and online shopping carts.
Why Learn PHP Numbers?
Understanding numbers is essential because almost every web application performs calculations, including:
- Shopping websites
- Inventory systems
- Payroll software
- Banking applications
- Analytics dashboards
- Invoice generators
- CRM systems
Mastering numeric operations will help you build reliable and efficient PHP applications.