PHP Operators

PHP operators are used to perform operations on variables and values. PHP has a variety of operators that allow you to perform different operations like arithmetic, comparison, logical, assignment, and more.

Types of Operators

1. Arithmetic Operators

These operators are used to perform common arithmetic operations like addition, subtraction, etc.

Operator Name Example
+ Addition $x + $y
- Subtraction $x - $y
* Multiplication $x * $y
/ Division $x / $y
% Modulus $x % $y

Example


<?php
$x = 10;
$y = 2;
            
echo $x + $y; // Addition
echo $x - $y; // Subtraction
echo $x * $y; // Multiplication
echo $x / $y; // Division
echo $x % $y; // Modulus
?>
                        

2. Assignment Operators

Assignment operators are used to assign values to variables.

Operator Example Description
= $x = $y Assigns the value of $y to $x
+= $x += $y Adds $y to $x
-= $x -= $y Subtracts $y from $x
*= $x *= $y Multiplies $y by $x
/= $x /= $y Divides $x by $y
%= $x %= $y Calculates the modulus of $x by $y

3. Comparison Operators

Comparison operators are used to compare two values.

Operator Name Example
== Equal $x == $y
!= Not Equal $x != $y
=== Identical $x === $y
!== Not Identical $x !== $y
> Greater Than $x > $y
< Less Than $x < $y

4. Logical Operators

Logical operators are used to combine conditional statements.

Operator Name Example
&& And $x && $y
|| Or $x || $y
! Not !$x

5. Increment/Decrement Operators

These operators are used to increment or decrement a variable's value.

Operator Name Example
++ Increment ++$x or $x++
-- Decrement --$x or $x--

6. String Operators

String operators are used to manipulate strings.

Operator Name Example
. Concatenation $x . $y
.= Concatenation Assignment $x .= $y

7. Array Operators

Array operators are used to compare or combine arrays.

Operator Name Example
+ Union $x + $y
== Equality $x == $y
=== Identity $x === $y
!= Inequality $x != $y
!== Non-identity $x !== $y

8. Conditional Assignment Operators

These operators are used to assign a value based on a condition.

Operator Name Example
?: Ternary $x = ($a > $b) ? $a : $b
?? Null Coalescing $x = $y ?? $z