Scroll
PHP Lessons - Lesson 6 - PHP Operators
We’ve already explored string and numeric variables, and learned that numeric variables in PHP can be of various types: integers, floats, booleans. Now it’s time to learn how to operate on them, modify them, and perform arithmetic.
Below are tables illustrating the use of different PHP operators.
Arithmetic Operators in PHP
PHP Operator | Description | Example | Result |
---|---|---|---|
+ | Addition | x=2 x+2 | 4 |
- | Subtraction | x=2 5-x | 3 |
* | Multiplication | x=4 x*5 | 20 |
/ | Division | 15/5 5/2 | 3 2.5 |
% | Modulus (remainder) | 5%2 10%8 10%2 | 1 2 0 |
++ | Increment (add 1) | x=5 x++ | x=6 |
-- | Decrement (subtract 1) | x=5 x-- | x=4 |
Examples:
<?php
$x = 1;
$y = 2;
$z = $x + $y;
print $z; // Output: 3
?>
<?php
$x = 10;
$y = $x % 3;
print $y; // Output: 1
?>
Time Calculation with Modulus
<?php
$time = time();
$hours = $time % 86400;
$hours = floor($hours / 3600);
$minutes = $time % 3600;
$minutes = floor($minutes / 60);
$seconds = $time % 60;
print $hours . ':' . $minutes . ':' . $seconds;
?>
What is Unix time?
Unix time is a system for describing points in time as the number of seconds that have elapsed since midnight UTC on January 1, 1970 (the Unix Epoch). It’s efficient for date calculations and storage.
Increment / Decrement
<?php
$x = 1;
$y = 1;
$x++;
$y = $y + 1;
print 'x=' . $x . '<br />';
print 'y=' . $y;
?>
// Both x and y will be 2
<?php
$x = 4;
$y = 4;
$x--;
$y = $y - 1;
print 'x=' . $x . '<br />';
print 'y=' . $y;
?>
// Both x and y will be 3
Assignment Operators in PHP
Operator | Example | Equivalent |
---|---|---|
= | x = y | x = y |
+= | x += y | x = x + y |
-= | x -= y | x = x - y |
*= | x *= y | x = x * y |
/= | x /= y | x = x / y |
.= | x .= y | x = x . y (string concat) |
%= | x %= y | x = x % y |
Comparison Operators in PHP
Operator | Description | Example |
---|---|---|
== | Equal | 5 == 8 // false |
!= | Not equal | 5 != 8 // true |
<> | Not equal | 5 <> 8 // true |
> | Greater than | 5 > 8 // false |
< | Less than | 5 < 8 // true |
>= | Greater or equal | 5 >= 8 // false |
<= | Less or equal | 5 <= 8 // true |
We will cover comparison operators in more detail when discussing conditional statements and loops.
Logical Operators in PHP
Operator | Description | Example |
---|---|---|
&& | AND |
x = 6, y = 3 (x < 10 && y > 1) // true |
|| | OR |
x = 6, y = 3 (x == 5 || y == 5) // false |
! | NOT |
x = 6, y = 3 !(x == y) // true |
These operators will also be covered in more depth in upcoming lessons on control structures.