What are the Types of PHP Operators ? Give Examples

Operators in PHP are symbols used to perform operations on variables and values. They are essential for performing arithmetic calculations, comparisons, logical operations, and more. Understanding PHP operators is crucial for writing efficient and functional scripts.


Types of PHP Operators

1. Arithmetic Operators

Used to perform mathematical calculations.

OperatorDescriptionExampleResult
+Addition$a + $bSum
-Subtraction$a - $bDifference
*Multiplication$a * $bProduct
/Division$a / $bQuotient
%Modulus$a % $bRemainder
**Exponentiation$a ** $bPower

Example:

<?php
$a = 10;
$b = 3;
echo $a + $b; // 13
echo $a % $b; // 1
?>

2. Assignment Operators

Used to assign values to variables.

OperatorDescriptionExample
=Simple assignment$a = 5;
+=Add and assign$a += 3;
-=Subtract and assign$a -= 2;
*=Multiply and assign$a *= 2;
/=Divide and assign$a /= 2;
%=Modulus and assign$a %= 3;

3. Comparison Operators

Used to compare two values.

OperatorDescriptionExample
==Equal$a == $b
===Identical (value & type)$a === $b
!=Not equal$a != $b
!==Not identical$a !== $b
>Greater than$a > $b
<Less than$a < $b
>=Greater or equal$a >= $b
<=Less or equal$a <= $b

Example:

<?php
$a = 5;
$b = 10;
if ($a < $b) {
    echo "$a is less than $b";
}
?>

4. Logical Operators

Used to combine conditional statements.

OperatorDescriptionExample
&&And$a && $b
``
!Not!$a
andAnd (lower precedence)$a and $b
orOr (lower precedence)$a or $b

5. Increment / Decrement Operators

Used to increase or decrease variable values by 1.

<?php
$a = 5;
$a++; // Increment, now 6
$a--; // Decrement, now 5
?>

6. String Operators

Used to work with strings.

OperatorDescriptionExample
.Concatenation$a . $b
.=Concatenate and assign$a .= $b

Example:

<?php
$greet = "Hello";
$greet .= " World!";
echo $greet; // Outputs: Hello World!
?>

7. Array Operators

Used to compare arrays or combine them.

OperatorDescription
+Union of arrays
==Equality
===Identity (equal & same order)
!=Not equal
!==Not identical

Best Practices

  • Use the correct operator type for your operation to avoid unexpected results.
  • Be careful with comparison operators, especially == vs ===.
  • Use parentheses () to ensure order of operations is correct in complex expressions.
  • Combine logical operators carefully to avoid logical errors in conditions.

External Reference: PHP Manual

View Other Articles About PHP: Learn PHP Articles

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *