Operators in PHP allow us to perform operations on data. Operators can be classified into different categories, including arithmetic operators, comparison operators, logical operators, and more. Each of these categories has specific functions that we will explain in more detail below.
Arithmetic operators include addition, subtraction, multiplication, and division. These operators are commonly used in basic mathematics and can be easily utilized. For example, in a sales system, these operators are used to calculate the total price of products.
Comparison operators are mostly used for examining relationships between quantities or logical conditions. This type of operator allows us to compare two or several values and receive a correct (True) or incorrect (False) result. These operators are typically used in situations that require decision-making, such as in if-else conditions.
Logical operators establish a relationship between logical quantities. For instance, if we want to evaluate a combination of conditions, we would use logical operators. This category includes AND, OR, and NOT, which are frequently used in many decision-making situations.
In continuation, we will provide examples indicating the situations where these operators are used.
<?php
// Arithmetic operators
$a = 10;
$b = 5;
$sum = $a + $b; // Addition
$diff = $a - $b; // Subtraction
$prod = $a * $b; // Multiplication
$quot = $a / $b; // Division
// Comparison operators
$equal = ($a == $b); // Equals
$greater = ($a > $b); // Greater than
// Logical operators
$logicalAnd = ($a > 5) && ($b < 10);
$logicalOr = ($a > 100) || ($b < 10);
?>
Line by Line Explanation
$a = 10;
assigns the value 10 to the variable a
.
$b = 5;
assigns the value 5 to the variable b
.
$sum = $a + $b;
stores the sum of a
and b
in sum
.
$diff = $a - $b;
stores the result of b
subtracted from a
in diff
.
$prod = $a * $b;
stores the product of a
and b
in prod
.
$quot = $a / $b;
stores the division of a
by b
in quot
.
$equal = ($a == $b);
checks whether a
is equal to b
and assigns the result to equal
.
$greater = ($a > $b);
checks whether a
is greater than b
and assigns the result to greater
.
$logicalAnd = ($a > 5) && ($b < 10);
checks whether a
is greater than 5 and b
is less than 10.
$logicalOr = ($a > 100) || ($b < 10);
checks whether a
is greater than 100 or b
is less than 10.