In PHP, operators are symbols that perform operations on variables and values. They are essential for performing calculations, comparisons, and logical operations. This tutorial will cover the basics of arithmetic, comparison, and logical operators in PHP.
Arithmetic operators are used to perform basic mathematical operations such as addition, subtraction, multiplication, division, modulus, and increment/decrement.
+): Adds two numbers.-): Subtracts the second number from the first.*): Multiplies two numbers./): Divides the first number by the second. If both operands are integers, the result is also an integer (integer division).%): Returns the remainder of a division operation.++): Increments a variable by one.--): Decrements a variable by one.Comparison operators are used to compare two values and return a boolean result (true or false).
==): Checks if two values are equal. It performs type juggling, meaning it will try to convert the operands to compatible types before comparison.===): Checks if two values are equal and of the same type.!=): Checks if two values are not equal. It also performs type juggling.!==): Checks if two values are not equal or not of the same type.>): Checks if the first value is greater than the second.<): Checks if the first value is less than the second.>=): Checks if the first value is greater than or equal to the second.<=): Checks if the first value is less than or equal to the second.Logical operators are used to combine conditional statements and return a boolean result.
&&): Returns true if both operands are true.||): Returns true if at least one of the operands is true.!): Inverts the boolean value of its operand. If the operand is true, it returns false, and vice versa.<?php
$a = 10;
$b = 5;
echo $a + $b; // Output: 15
echo $a - $b; // Output: 5
echo $a * $b; // Output: 50
echo $a / $b; // Output: 2
echo $a % $b; // Output: 0
$a++;
echo $a; // Output: 11
$b--;
echo $b; // Output: 4
?>
<?php
$x = 10;
$y = "10";
var_dump($x == $y); // bool(true)
var_dump($x === $y); // bool(false)
var_dump($x != $y); // bool(false)
var_dump($x !== $y); // bool(true)
var_dump($x > $y); // bool(false)
var_dump($x < $y); // bool(false)
var_dump($x >= $y); // bool(true)
var_dump($x <= $y); // bool(true)
?>
<?php
$condition1 = true;
$condition2 = false;
$resultAnd = $condition1 && $condition2; // false
$resultOr = $condition1 || $condition2; // true
$resultNot = !$condition1; // false
var_dump($resultAnd); // bool(false)
var_dump($resultOr); // bool(true)
var_dump($resultNot); // bool(false)
?>
Now that you have a good understanding of operators in PHP, the next step is to learn about control structures such as if statements, loops, and switch cases. These will allow you to write more complex and dynamic code.
Stay tuned for the next tutorial on control structures!