In PHP, numbers are used to represent numeric values, including integers and floating-point numbers (decimals). Here's how you work with numbers in PHP:
1. Integers:
Integers represent whole numbers, both positive and negative, without decimal points. They can be assigned directly to variables.
php
$age = 30; // Positive integer
$bankBalance = -50; // Negative integer
2. Floating-Point Numbers (Floats/Doubles):
Floating-point numbers represent numbers with decimal points. They can also be assigned directly to variables.
php
$pi = 3.14159;
$price = 19.99;
3. Arithmetic Operations:
PHP supports various arithmetic operations, such as addition, subtraction, multiplication, division, and more.
php
$a = 10;
$b = 5;
$sum = $a + $b; // Addition
$difference = $a - $b; // Subtraction
$product = $a * $b; // Multiplication
$quotient = $a / $b; // Division
4. Modulus (Remainder):
The modulus operator (`%`) gives the remainder of a division operation.
php
$remainder = $a % $b; // Remainder of 10 / 5 = 0
5. Increment and Decrement:
PHP provides increment (`++`) and decrement (`--`) operators to increase or decrease a variable by one.
php
$count = 0;
$count++; // $count is now 1
$count--; // $count is now 0 again
6. Number Formatting:
PHP offers functions to format numbers for display, such as `number_format()` and `sprintf()`.
php
$number = 1234567.89123;
echo number_format($number, 2); // Output: 1,234,567.89
7. Comparing Numbers:
Numbers can be compared using comparison operators (`==`, `===`, `<`, `>`, etc.).
php
$x = 10;
$y = 20;
if ($x < $y) {
echo "$x is less than $y";
}
8. Math Functions:
PHP provides a variety of math functions for more advanced operations, such as `abs()`, `sqrt()`, `pow()`, `round()`, and more.
php
$absValue = abs(-10); // Absolute value: 10
$squareRoot = sqrt(25); // Square root: 5
$power = pow(2, 3); // Power: 8
$rounded = round(3.7); // Round: 4
9. Type Conversion:
PHP can automatically convert between integer and floating-point values as needed.
php
$int = 5;
$float = 3.14;
$result = $int + $float; // Result is a float (8.14)
Remember that numbers are a fundamental part of programming and are used extensively for calculations, comparisons, and data manipulation in PHP.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc