Types of Operator in PHP

Types of Operators in PHP

PHP offers a variety of operators to perform different operations on variables and values. Here's a breakdown of the main types:

Arithmetic Operators

Used for mathematical calculations:

  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Division: /
  • Modulus (remainder): %
  • Exponentiation: ** (introduced in PHP 5.6)   

1. github.com

github.com

Assignment Operators

Used to assign values to variables:

  • Simple assignment: =
  • Addition assignment: +=
  • Subtraction assignment: -=
  • Multiplication assignment: *=
  • Division assignment: /=
  • Modulus assignment: %=
  • Exponentiation assignment: **= (introduced in PHP 5.6)   

 

Comparison Operators

Used to compare values:

  • Equal: ==
  • Identical: === (checks both value and type)
  • Not equal: !=
  • Not identical: !==
  • Greater than: >
  • Less than: <
  • Greater than or equal to: >=
  • Less than or equal to: <=

Logical Operators

Used to combine logical conditions:

  • And: && or AND
  • Or: || or OR
  • Not: !

Increment/Decrement Operators

Used to increment or decrement a variable's value by 1:

  • Pre-increment: ++ (before evaluation)
  • Post-increment: ++ (after evaluation)
  • Pre-decrement: -- (before evaluation)
  • Post-decrement: -- (after evaluation)

String Operators

Used to concatenate strings:

  • Concatenation: .

Array Operators

Used to manipulate arrays:

  • Union: +
  • Equality: ==
  • Inequality: !=

Bitwise Operators

Used to perform operations on individual bits of integers:

  • And: &
  • Or: |
  • Xor: ^
  • Not: ~
  • Left shift: <<
  • Right shift: >>

Type Operators

Used to check the type of a variable:

  • Type cast: (type)
  • Typeof operator: typeof

Example:

PHP

$x = 10; $y = 5; // Arithmetic operations

$sum = $x + $y;

$difference = $x - $y;

$product = $x * $y;

$quotient = $x / $y;

$remainder = $x % $y;

// Comparison operations

if ($x > $y) {    echo "x is greater than y"; }

// Logical operations

if ($x > 0 && $y > 0) {    echo "Both x and y are positive"; }

// String concatenation

$greeting = "Hello, " . "world!";

Use code with caution.

 

These operators are fundamental to PHP programming and are used extensively in various contexts to perform different operations and control the flow of your code.

 Sources and related content