Day 5: PHP Operators
PHP operators allow you to perform operations on variables and values. We’ll cover different types of operators including arithmetic, assignment, comparison, logical, and increment/decrement operators.
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Example:
[mycode]
<?php
$a = 10;
$b = 5;
echo “Addition: ” . ($a + $b) . “<br>”; // Output: 15
echo “Subtraction: ” . ($a – $b) . “<br>”; // Output: 5
echo “Multiplication: ” . ($a * $b) . “<br>”; // Output: 50
echo “Division: ” . ($a / $b) . “<br>”; // Output: 2
echo “Modulus: ” . ($a % $b) . “<br>”; // Output: 0
?>
[/mycode]
Assignment Operators
Assignment operators are used to assign values to variables.
Example:
[mycode]
<?php
$a = 10;
$a += 5;// Equivalent to $a = $a + 5;
echo $a; // Output: 15
?>
[/mycode]
Logical Operators
Logical operators are used to combine conditional statements.
[mycode]
<?php
$a = true;
$b = false;
echo ($a && $b) ? “True” : “False”; // Output: False
echo “<br>”;
echo ($a || $b) ? “True” : “False”; // Output: True
echo “<br>”;
echo (!$a) ? “True” : “False”; // Output: False
?>
[/mycode]
Increment/Decrement Operators
Increment and decrement operators are used to increment or decrement a variable’s value by 1.
[mycode]
<?php
$a = 10;
echo ++$a; // Output: 11
echo “<br>”;
echo $a++; // Output: 11 (then $a becomes 12)
echo “<br>”;
echo $a; // Output: 12
?>
[/mycode]
Next Steps
Practice using these operators in various expressions and conditional statements. In Day 6, we will explore control structures in PHP, including conditional statements and loops. Let me know if you have any questions or if you’re ready to move forward!