PHP Operators
PHP Operators
Introduction
• Operators are symbols that tell the PHP processor to
perform certain actions.
- Arithmetic operators
- Assignment operators
- Comparison operators
- Increment/Decrement operators
- String operators
- Array operators
- Conditional assignment operators
- Logical operators
Arithmetic operators
• The PHP arithmetic operators are used with numeric
values to perform common arithmetical operations, such
as addition, subtraction, multiplication etc.
Operator Description Example Result
+ Addition $x + $y Sum of $x and $y
OUTPUT:
Hello World!
Hello World!
PHP Conditional Assignment Operators
• The PHP conditional assignment operators are used to
set a value depending on conditions:
?: Ternary $x = expr1 ? expr2 : expr3 Returns the value of $x.
The value of $x is expr2 if expr1 = TRUE.
The value of $x is expr3 if expr1 = FALSE
$user = "Michael";
echo $status = (empty($user)) ? "anonymous" : $user;
?>
OUTPUT:
anonymous
Michael
PHP Conditional Assignment
Operators(contd.) – Null coalescing
<?php
echo $status = $user ?? 'anonymous';
echo "<br>";
$user = "Michael";
echo $status = $user ?? 'anonymous';
?>
OUTPUT:
anonymous
Michael
Logical Operators
• The logical operators are typically used to combine
conditional statements.
Operator Name Example Result
and And $x and $y True if both $x and $y are
true
or Or $x or $y True if either $x or $y is
true
xor Xor $x xor $y True if either $x or $y is
true, but not both
&& And $x && $y True if both $x and $y are
true
|| Or $x || $y True if either $x or $y is
true
! Not !$x True if $x is not true
Logical Operators(contd.)
<?php
$year = 2014;
// Leap years are divisible by 400 or by 4 but not 100
if(($year % 400 == 0) || (($year % 100 != 0) && ($year % 4 ==
0))){
echo "$year is a leap year.";
} else{
echo "$year is not a leap year.";
}
?>
OUTPUT:
2014 is not a leap year.