Start Coding

Topics

PHP Operators

PHP operators are symbols used to perform operations on variables and values. They are essential for manipulating data and controlling program flow in PHP scripts.

Types of PHP Operators

1. Arithmetic Operators

Arithmetic operators perform mathematical calculations on numeric values.

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)
  • Modulus (%)
  • Exponentiation (**)

Example:


$a = 10;
$b = 3;
echo $a + $b;  // Output: 13
echo $a % $b;  // Output: 1
    

2. Assignment Operators

Assignment operators are used to assign values to variables. The basic assignment operator is =, but PHP also provides combined operators like +=, -=, *=, etc.

Example:


$x = 5;
$x += 3;  // Equivalent to $x = $x + 3
echo $x;  // Output: 8
    

3. Comparison Operators

Comparison operators compare two values and return a boolean result.

  • Equal (==)
  • Identical (===)
  • Not equal (!=)
  • Greater than (>)
  • Less than (<)
  • Greater than or equal to (>=)
  • Less than or equal to (<=)

4. Logical Operators

Logical operators combine conditional statements.

  • AND (&&)
  • OR (||)
  • NOT (!)

Example:


$a = true;
$b = false;
var_dump($a && $b);  // Output: bool(false)
var_dump($a || $b);  // Output: bool(true)
    

5. Increment/Decrement Operators

These operators increase or decrease a variable's value by one.

  • Pre-increment (++$var)
  • Post-increment ($var++)
  • Pre-decrement (--$var)
  • Post-decrement ($var--)

6. String Operator

The concatenation operator (.) is used to combine two string values.

Example:


$str1 = "Hello";
$str2 = "World";
echo $str1 . " " . $str2;  // Output: Hello World
    

Operator Precedence

PHP follows a specific order when evaluating expressions with multiple operators. Parentheses can be used to explicitly define the order of operations.

Best Practices

  • Use parentheses to clarify complex expressions
  • Be cautious when comparing floating-point numbers due to precision issues
  • Use === for strict comparisons to avoid type juggling
  • Understand the difference between = (assignment) and == (comparison)

Mastering PHP operators is crucial for effective programming. They form the foundation for PHP Conditional Statements and are extensively used in PHP Loops. For more advanced usage, explore PHP Functions and PHP Arrays.