Operators (Arithmetic, Comparison, Logical)
Operators in PHP are symbols that perform operations on variables and values. They are essential for performing calculations, comparing values, and making logical decisions in your code. PHP supports several types of operators, including arithmetic, comparison, and logical operators.
Arithmetic
Operators
Arithmetic operators are used to
perform basic mathematical operations.
Example:
<?php
$a
= 10;
$b
= 3;
echo
$a + $b; // 13
echo
$a - $b; // 7
echo
$a * $b; // 30
echo
$a / $b; // 3.3333
echo
$a % $b; // 1 (modulus)
echo
$a ** $b; // 1000 (exponentiation)
?>
Comparison
Operators
Comparison operators are used to
compare two values. They return true or false.
Example:
<?php
$x
= 5;
$y
= 10;
var_dump($x
== $y); // false
var_dump($x
!= $y); // true
var_dump($x
=== $y); // false (checks value and type)
var_dump($x
!== $y); // true
var_dump($x
> $y); // false
var_dump($x
< $y); // true
var_dump($x
>= 5); // true
var_dump($y
<= 10); // true
?>
Logical
Operators
Logical operators are used to
combine multiple conditions and return true or false.
Example:
<?php
$a
= true;
$b
= false;
var_dump($a
&& $b); // false (AND)
var_dump($a
|| $b); // true (OR)
var_dump(!$a); // false (NOT)
var_dump($a
xor $b); // true (exclusive OR)
?>