PHP Operators

Learn about operators in PHP, their types, and usage.

What Are Operators?

Operators are special symbols in PHP that perform operations on variables and values. They can be used for arithmetic, comparison, logical operations, and more.

Types of Operators

  • Arithmetic Operators: Used for mathematical calculations.
  • Assignment Operators: Used to assign values to variables.
  • Comparison Operators: Used to compare two values.
  • Logical Operators: Used to combine conditional statements.
  • Increment/Decrement Operators: Used to increase or decrease the value of a variable.
  • String Operators: Used to concatenate strings.

1. Arithmetic Operators

Arithmetic operators perform basic mathematical operations:

  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Division: /
  • Modulus: % (remainder of division)

Example:

<?php
$x = 10;
$y = 3;
echo $x + $y; // Outputs: 13
echo $x - $y; // Outputs: 7
echo $x * $y; // Outputs: 30
echo $x / $y; // Outputs: 3.3333
echo $x % $y; // Outputs: 1
?>

2. Assignment Operators

Assignment operators are used to assign values to variables:

  • Simple Assignment: =
  • Add and Assign: +=
  • Subtract and Assign: -=
  • Multiply and Assign: *=
  • Divide and Assign: /=
  • Modulus and Assign: %=

Example:

<?php
$x = 10;
$x += 5; // Now $x is 15
$x -= 3; // Now $x is 12
?>

3. Comparison Operators

Comparison operators are used to compare two values:

  • Equal: ==
  • Identical: === (equal and same type)
  • Not Equal: != or <>
  • Not Identical: !==
  • Greater Than: >
  • Less Than: <
  • Greater Than or Equal To: >=
  • Less Than or Equal To: <=

Example:

<?php
$x = 10;
$y = 20;
var_dump($x == $y); // Outputs: false
var_dump($x < $y); // Outputs: true
?>

4. Logical Operators

Logical operators are used to combine multiple conditions:

  • AND: && (both conditions must be true)
  • OR: || (at least one condition must be true)
  • NOT: ! (inverts the boolean value)

Example:

<?php
$x = 10;
$y = 20;
if ($x < $y && $y > 15) {
    echo "Both conditions are true.";
}
?>

5. Increment/Decrement Operators

These operators are used to increase or decrease the value of a variable by 1:

  • Increment: ++
  • Decrement: --

Example:

<?php
$x = 10;
$x++; // $x is now 11
$y = 5;
$y--; // $y is now 4
?>

6. String Operators

The string operator is used to concatenate (combine) two strings:

  • Concatenation: .
  • Concatenation Assignment: .=

Example:

<?php
$firstName = "John";
$lastName = "Doe";
$fullName = $firstName . " " . $lastName; // Outputs: John Doe
?>

Conclusion

PHP operators are fundamental for performing operations on variables and values. Understanding the different types of operators will help you write effective PHP scripts.