In PHP, operators are special symbols used to perform operations on variables and values. Operators help you perform a variety of tasks, such as mathematical calculations, string manipulations, logical comparisons, and more. Understanding operators is essential for writing effective and efficient PHP code. PHP operators are categorized into several types:
Let us now learn about each of these operators in detail.
1. Arithmetic Operators
Arithmetic operators are used to perform basic arithmetic operations like addition, subtraction, multiplication, division, and modulus.
Operator | Name | Syntax | Operation |
|---|---|---|---|
+ | Addition | $x + $y | Sum the operands |
- | Subtraction | $x - $y | Differences in the Operands |
* | Multiplication | $x * $y | Product of the operands |
/ | Division | $x / $y | The quotient of the operands |
** | Exponentiation | $x ** $y | $x raised to the power $y |
% | Modulus | $x % $y | The remainder of the operands |
Note: The exponentiation has been introduced in PHP 5.6.
Example: This example explains the arithmetic operators in PHP.
<?php
// Define two numbers
$x = 10;
$y = 3;
// Addition
echo "Addition: " . ($x + $y) . "\n";
// Subtraction
echo "Subtraction: " . ($x - $y) . "\n";
// Multiplication
echo "Multiplication: " . ($x * $y) . "\n";
// Division
echo "Division: " . ($x / $y) . "\n";
// Exponentiation
echo "Exponentiation: " . ($x ** $y) . "\n";
// Modulus
echo "Modulus: " . ($x % $y) . "\n";
?>
Output
Addition: 13 Subtraction: 7 Multiplication: 30 Division: 3.3333333333333 Exponentiation: 1000 Modulus: 1
2. Logical Operators
Logical operators are used to operate with conditional statements. These operators evaluate conditions and return a boolean result (true or false).
Operator | Name | Syntax | Operation |
|---|---|---|---|
| and | Logical AND | $x and $y | True if both the operands are true else false |
| or | Logical OR | $x or $y | True if either of the operands is true otherwise, it is false |
| xor | Logical XOR | $x xor $y | True if either of the operands is true and false if both are true |
| && | Logical AND | $x && $y | True if both the operands are true else false |