PHP Operators

In PHP, operators are used to perform operations on variables and values. PHP provides a wide range of operators, including arithmetic operators, comparison operators, logical operators, and assignment operators.

Here are some examples of commonly used operators in PHP:

  1. Arithmetic Operators – Used to perform mathematical operations on values
$num1 = 5;
$num2 = 3;
$sum = $num1 + $num2; // Addition operator
$diff = $num1 - $num2; // Subtraction operator
$prod = $num1 * $num2; // Multiplication operator
$quot = $num1 / $num2; // Division operator
$mod = $num1 % $num2; // Modulus operator
echo $sum, " ", $diff, " ", $prod, " ", $quot, " ", $mod; // Output: 8 2 15 1.6666666666667 2

In this example, the arithmetic operators are used to perform addition, subtraction, multiplication, division, and modulus operations on the variables $num1 and $num2. The resulting values are then assigned to the variables $sum, $diff, $prod, $quot, and $mod, respectively. The echo statement is then used to print the values to the screen.

  1. Comparison Operators – Used to compare values and return a Boolean value of true or false
$num1 = 5;
$num2 = 3;
$is_greater = $num1 > $num2; // Greater than operator
$is_less = $num1 < $num2; // Less than operator
$is_equal = $num1 == $num2; // Equal to operator
$is_not_equal = $num1 != $num2; // Not equal to operator
$is_greater_or_equal = $num1 >= $num2; // Greater than or equal to operator
$is_less_or_equal = $num1 <= $num2; // Less than or equal to operator
echo $is_greater, " ", $is_less, " ", $is_equal, " ", $is_not_equal, " ", $is_greater_or_equal, " ", $is_less_or_equal; // Output: 1 0 0 1 1 0

In this example, the comparison operators are used to compare the values of the variables $num1 and $num2. The resulting Boolean values of true or false are then assigned to the variables $is_greater, $is_less, $is_equal, $is_not_equal, $is_greater_or_equal, and $is_less_or_equal, respectively. The echo statement is then used to print the values to the screen.

  1. Logical Operators – Used to perform logical operations on Boolean values
$num1 = 5;
$num2 = 3;
$is_greater = $num1 > $num2; // Greater than operator
$is_less = $num1 < $num2; // Less than operator
$is_equal = $num1 == $num2; // Equal to operator
$logical_and = $is_greater && $is_less; // Logical AND operator
$logical_or = $is_greater || $is_less; // Logical OR operator
$logical_not = !$is_equal; // Logical NOT operator
echo $logical_and, " ", $logical_or, " ", $logical_not; // Output: 0 1 1

In this example, the logical operators are used to perform logical operations on the Boolean values of the variables $is_greater, $is_less, and $is_equal. The resulting Boolean values of true or false are then