
Understanding PHP operators, especially arithmetic and comparison operators, is crucial for performing calculations and making logical decisions in code. In this blog, we will explore these operators with examples.
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations on numeric values. Below are the arithmetic operators in PHP:
Examples
1. Basic Arithmetic Operations
$a = 10; $b = 5; echo "Addition: " . ($a + $b) . "<br>"; echo "Subtraction: " . ($a - $b) . "<br>"; echo "Multiplication: " . ($a * $b) . "<br>"; echo "Division: " . ($a / $b) . "<br>"; echo "Modulus: " . ($a % $b) . "<br>"; echo "Exponentiation: " . ($a ** $b) . "<br>";
2. Real-world Usage: Calculating Discounts
$originalPrice = 100; $discount = 20; $finalPrice = $originalPrice - ($originalPrice * $discount / 100); echo "The final price after discount is: $finalPrice";
Comparison Operators
Comparison operators are used to compare two values. They return true
or false
based on the condition.
Examples
1. Basic Comparison Operations
$x = 10; $y = "10"; var_dump($x == $y); // true (values are the same) var_dump($x === $y); // false (different types) var_dump($x != $y); // false var_dump($x !== $y); // true var_dump($x > 5); // true var_dump($x <= 10); // true
2. Real-world Usage: User Age Validation
$age = 18; if ($age >= 18) { echo "You are eligible to vote."; } else { echo "You are not eligible to vote."; }
Conclusion
Understanding arithmetic and comparison operators in PHP is essential for writing efficient code. Arithmetic operators allow you to perform mathematical operations, while comparison operators help in decision-making processes. By mastering these operators, you can build more dynamic and logical PHP applications.
Leave a Comment