PHP : Operators

In PHP, operators are special symbols or keywords used to perform operations on variables and values. PHP supports various types of operators, including arithmetic, assignment, comparison, logical, and string operators. Here's an overview of some commonly used operators in PHP:

1. Arithmetic Operators:

 

  •   Addition (`+`), Subtraction (`-`), Multiplication (`*`), Division (`/`), Modulus (`%`), and Exponentiation (`**`).
  •   Example:

    
     $a = 10;
     $b = 5;
     echo $a + $b; // Output: 15

     

2. Assignment Operators:

 

  •   Assigns a value to a variable.
  •   Example:

   
     $x = 10;
     $x += 5; // Equivalent to: $x = $x + 5;

   

3. Comparison Operators:

 

  •   Compare two values and return a boolean result (`true` or `false`).
  •   Example:

    
     $a = 10;
     $b = 5;
     var_dump($a > $b); // Output: bool(true)

     

4. Logical Operators:

 

  •    Combine multiple conditions and return a boolean result.
  •    Logical AND (`&&`), Logical OR (`||`), Logical NOT (`!`).
  •    Example:

     
     $a = 10;
     $b = 5;
     if ($a > 0 && $b > 0) {
         // Both conditions are true
     }

     

5. String Operators:

  •   Concatenates two strings.
  •   Example:

  
     $str1 = "Hello, ";
     $str2 = "world!";
     echo $str1 . $str2; // Output: Hello, world!

     

6. **Increment/Decrement Operators**:

 

  •   Increment (`++`), Decrement (`--`).
  •   Example:

    
     $x = 5;
     echo ++$x; // Output: 6

     

7. Ternary Operator:

 

  •    Short form of an if-else statement.
  •    Syntax: condition ? value_if_true : value_if_false.
  •    Example:

   
     $age = 20;
     $status = ($age >= 18) ? "adult" : "minor";

     

These are just a few examples of the many operators available in PHP. Operators are essential for performing various operations in PHP scripts, including arithmetic calculations, logical evaluations, and string manipulations. Understanding how to use operators effectively is crucial for writing PHP code efficiently.