Different operators in PHP

Here we will learn about different operators in PHP. We use these operators in calculations and comparisons. Different types of operators that we use on variables are:

  1. Arithmetic operators
  2. Comparison operators
  3. Increment/Decrement operators
  4. Logical operators
  5. Conditional assignment operators
  6. Assignment operators
  7. String operators and more.

Arithmetic operators in PHP

These operators are used for arithmetic calculations like addition, subtraction and more

For example:

<?php
$a = 2;  
$b = 3;

echo $a + $b;
?>

You only need to specify the operators like +, -, /, %, etc according to the calculations.

Assignment operators in PHP

The assignment operators assign variables to specific values.

let us look at an example:

<?php
$a = 3;  
echo $a;
?>

Output:3

Another example of adding two variables:

<?php
$a = 10;  
$a += 10;

echo $a;
?>  

In the above code, we need to replace x -= y, x *= y, x /= y for doing subtraction, multiplication, and division respectively.

Comparison operators in PHP

These operators are for comparison of the variables.

<?php
$a = 10;  
$b = "10";

var_dump($a == $b);
?>

The output will be: bool(true)

Another example to check greater than and equal to an assignment.

<?php
$a = 10;
$b = 10;

var_dump($a >= $b);

Output: bool(true)

Logical operators in PHP

These are used in conditional statements. Different types of logical operators are and, or, xor, &&, ||, etc.

For example:

<?php
$a = 10;  
$b = 5;

if ($a == 10 and $b == 5) {
    echo "yes";
}
?>

Output: yes

<?php
$a = 10;  
$b = 5;

if ($a == 10 && $b == 5) {
    echo "yes";
}
?>

Output: yes

Array operators in PHP

Here the operators are used to compare arrays.

For example:

<?php
$v = array("a" => "red");  
$t = array("c" => "blue");  

print_r($v + $t); 
?>

The above-discussed operators are the basic ones, but we do have many other operators for advance calculations like string, increment, decrement operators.

Also read: Modulus operator in PHP

Leave a Reply

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