PHP operators are used to perform operations on variables and values. They can be categorized into several types:
PHP provides several operators, which can be divided into the following categories:
The following example demonstrates the use of arithmetic operators in PHP:
<?php
$var1 = 10;
$var2 = 5;
echo "Addition: " . ($var1 + $var2) . "<br>";
echo "Subtraction: " . ($var1 - $var2) . "<br>";
echo "Multiplication: " . ($var1 * $var2) . "<br>";
echo "Division: " . ($var1 / $var2) . "<br>";
echo "Modulus: " . ($var1 % $var2) . "<br>";
?>
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2
Modulus: 0
The following example demonstrates the use of comparison operators:
<?php
$var1 = 10;
$var2 = 20;
echo "Is \$var1 equal to \$var2? " . ($var1 == $var2 ? 'Yes' : 'No') . "<br>";
echo "Is \$var1 not equal to \$var2? " . ($var1 != $var2 ? 'Yes' : 'No') . "<br>";
echo "Is \$var1 greater than \$var2? " . ($var1 > $var2 ? 'Yes' : 'No') . "<br>";
echo "Is \$var1 less than \$var2? " . ($var1 < $var2 ? 'Yes' : 'No') . "<br>";
?>
Is $var1 equal to $var2? No
Is $var1 not equal to $var2? Yes
Is $var1 greater than $var2? No
Is $var1 less than $var2? Yes
The following example demonstrates the use of increment and decrement operators:
<?php
$var = 5;
echo "Initial value: " . $var . "<br>";
echo "Incremented value: " . ++$var . "<br>";
echo "Decremented value: " . --$var . "<br>";
?>
Initial value: 5
Incremented value: 6
Decremented value: 5
PHP operators are fundamental to performing various operations in programming. Understanding them allows you to manipulate values effectively in your PHP scripts.