Explain operators used in PHP with the help of a program
Operators in PHP are symbols or characters that perform specific operations on
operands (variables, values, or expressions).
1. Arithmetic Operators:
- Addition (+): Adds two operands.
- Subtraction (-): Subtracts the second operand from the first.
- Multiplication (*): Multiplies two operands.
- Division (/): Divides the first operand by the second.
- Modulus (%): Returns the remainder of the division.
- Increment (++) and Decrement (--): Increases or decreases the value of an
operand by 1.
```php
<?php
$a = 10;
$b = 5;
// Arithmetic operators
$sum = $a + $b; // 10 + 5 = 15
$difference = $a - $b; // 10 - 5 = 5
$product = $a * $b; // 10 * 5 = 50
$quotient = $a / $b; // 10 / 5 = 2
$remainder = $a % $b; // 10 % 5 = 0
// Increment and decrement operators
$a++; // $a is now 11
$b--; // $b is now 4
echo "Sum: " . $sum . "\n";
echo "Difference: " . $difference . "\n";
echo "Product: " . $product . "\n";
echo "Quotient: " . $quotient . "\n";
echo "Remainder: " . $remainder . "\n";
echo "Incremented a: " . $a . "\n";
echo "Decremented b: " . $b . "\n";
?>
```
2. Assignment Operators:
- Assignment (=): Assigns a value to a variable.
- Compound assignment operators (e.g., +=, -=, *=, /=): Perform an operation
and assign the result to the variable.
```php
<?php
$x = 10;
$y = 5;
// Assignment operator
$result = $x + $y; // $result is assigned the value 15
// Compound assignment operator
$x += $y; // Equivalent to $x = $x + $y; (15)
$y *= 2; // Equivalent to $y = $y * 2; (10)
echo "Result: " . $result . "\n";
echo "Updated x: " . $x . "\n";
echo "Updated y: " . $y . "\n";
?>
```
3. Comparison Operators:
- Equal to (==): Checks if two values are equal.
- Identical to (===): Checks if two values are equal and of the same type.
- Not equal to (!= or <>): Checks if two values are not equal.
- Not identical to (!==): Checks if two values are not equal or not of the same
type.
- Greater than (>): Checks if the first value is greater than the second.
- Less than (<): Checks if the first value is less than the second.
- Greater than or equal to (>=): Checks if the first value is greater than or
equal to the second.
- Less than or equal to (<=): Checks if the first value is less than or equal to
the second.
```php
<?php
$a = 10;
$b = 5;
// Comparison operators
0 Comments