PHP Expressions - Operators
PHP Expressions - Operators
Presented By:-
Er. Yatika Hasija
Assistant Professor
CSE Department
Lovely Professional University
PHP Expressions
Almost everything in a PHP script is an expression.
Anything that has a value is an expression.
In a typical assignment statement ($x=100), a literal value,
a function or operands processed by operators is an
expression, anything that appears to the right of
assignment operator (=)
Expression
• $x=100; //100 is an expression
• $a=$b+$c; //b+$c is an expression
• $c=add($a,$b); //add($a,$b) is an expresson
• $val=sqrt(100); //sqrt(100) is an expression
• $var=$x!=$y; //$x!=$y is an expression
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;
?>
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
Example
<?php
$x = 50;
$y = 30;
if ($x == 50 and $y == 30)
echo "and Success \n";
if ($x == 50 or $y == 20)
echo "or Success \n";
if ($x == 50 || $y == 20)
echo "|| Success \n";
if (!$z)
echo "! Success \n";
?>
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.
Spaceship Operators: