PHP Operators

 PHP Operators

PHP Operator is a symbol that performs specific operations on operands.

In simple words, operators are used to performing operations on variables or values. Operands are used to store or hold value.

Classification of operators (according to operands)

operators can be categorized into four categories according to operands −

·         Unary prefix operators, which use a single operand.

·         Binary operators, which take two operands ex.  Used in arithmetic and logical operations.

·         The conditional operator (a ternary operator), which takes three operands and evaluates either the second or third expression, depending on the evaluation of the first expression.

 

Classification of operators (according to functions)

1.       Increment/Decrement Operators

2.       Arithmetic operators

3.       Assignment operators

4.       Comparison operators

5.       Logical operators

6.       String operators

7.       Array operators

8.       Conditional assignment (or ternary) Operators

9.       Spaceship Operators (Introduced in PHP 7)

10.    Bitwise operator

 

1.     Increment/Decrement Operators

These are called the unary operators as they work on single operands. These are used to increment or decrement values.

OPERATOR

NAME

SYNTAX

OPERATION

++

Pre-Increment

++$x

First increments $x by one, then return $x

Pre-Decrement

–$x

First decrements $x by one, then return $x

++

Post-Increment

$x++

First returns $x, then increment it by one

Post-Decrement

$x–

First returns $x, then decrement it by one

 

Example:

 

<?php

  $x = 2;

echo ++$x, " Increments first then assign \n";

echo $x, "\n";

  $x = 2;

echo $x++, " Assign first then increments \n";

echo $x, "\n";

  $x = 2;

echo --$x, " Decrements first then Assign \n";

echo $x, "\n";

  $x = 2;

echo $x--, " Assign first then decrements \n";

echo $x;

  ?>

Output:

3 Increments first then assign

3

2 Assign first then increments

3

1 Decrements first then Assign

1

2 Assign first then decrements

1

=====================================================================

 

2.                PHP Arithmetic Operators

The PHP arithmetic operators are binary operators used with numeric values to perform common arithmetical operations, such as addition, subtraction, multiplication, etc.

 

Operator

Name

Example

Result

+

Addition

$x + $y

Sum of $x and $y

-

Subtraction

$x - $y

Difference of $x and $y

*

Multiplication

$x * $y

Product of $x and $y

/

Division

$x / $y

Quotient of $x and $y

%

Modulus

$x % $y

Remainder of $x divided by $y

**

Exponentiation

$x ** $y

Result of raising $x to the $y'th power

 

Example:-

<html>

      <head>

      <title>Arithmetical Operators</title>

   </head>

      <body>

         <?php

         $a = 42;

         $b = 20;

                 $c = $a + $b;

         echo "Addtion Operation Result: $c <br/>";

               $c = $a - $b;

         echo "Substraction Operation Result: $c <br/>";

               $c = $a * $b;

         echo "Multiplication Operation Result: $c <br/>";

                 $c = $a / $b;

         echo "Division Operation Result: $c <br/>";

                  $c = $a % $b;

         echo "Modulus Operation Result: $c <br/>";

                 $c = $a++;

         echo "Increment Operation Result: $c <br/>";

                  $c = $a--;

         echo "Decrement Operation Result: $c <br/>";

      ?>

      </body>

</html>

 

Outputs −

Addition Operation Result: 62

Subtraction Operation Result: 22

Multiplication Operation Result: 840

Division Operation Result: 2.1

Modulus Operation Result: 2

Increment Operation Result: 42

Decrement Operation Result: 43

 

=====================================================================

3.     PHP Assignment Operators (compound opt.)

The PHP assignment operators are used with numeric values to write a value to a variable.

The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the assignment expression on the right.

 

Assignment

Same as...

Description

x = y

x = y

The left operand gets set to the value of the expression on the right

x += y

x = x + y

Addition

x -= y

x = x - y

Subtraction

x *= y

x = x * y

Multiplication

x /= y

x = x / y

Division

x %= y

x = x % y

Modulus

 

EXAMPLE:-

<html>

  

   <head>

      <title>Assignment Operators</title>

   </head>

  

   <body>

     

      <?php

         $a = 42;

         $b = 20;

        

         $c = $a + $b; 

         echo "Addtion Operation Result: $c <br/>";

        

         $c += $a; 

         echo "Add AND Assigment Operation Result: $c <br/>";

        

         $c -= $a;

         echo "Subtract AND Assignment Operation Result: $c <br/>";

        

         $c *= $a;

         echo "Multiply AND Assignment Operation Result: $c <br/>";

        

         $c /= $a;

         echo "Division AND Assignment Operation Result: $c <br/>";

        

         $c %= $a;

         echo "Modulus AND Assignment Operation Result: $c <br/>";

      ?>

     

   </body>

</html>

 

OUTPUT:-

Addtion Operation Result: 62

Add AND Assigment Operation Result: 104

Subtract AND Assignment Operation Result: 62

Multiply AND Assignment Operation Result: 2604

Division AND Assignment Operation Result: 62

Modulus AND Assignment Operation Result: 20

=====================================================================

4.     PHP Comparison Operators

The PHP comparison operators are used to compare two values (number or string):

 

Operator

Name

Example

Result

==

Equal

$x == $y

Returns true if $x is equal to $y

===

Identical

$x === $y

Returns true if $x is equal to $y, and they are of the same type

!=

Not equal

$x != $y

Returns true if $x is not equal to $y

<> 

Not equal

$x <> $y

Returns true if $x is not equal to $y

!==

Not identical

$x !== $y

Returns true if $x is not equal to $y, or they are not of the same type

> 

Greater than

$x > $y

Returns true if $x is greater than $y

< 

Less than

$x < $y

Returns true if $x is less than $y

>=

Greater than or equal to

$x >= $y

Returns true if $x is greater than or equal to $y

<=

Less than or equal to

$x <= $y

Returns true if $x is less than or equal to $y

<=>

Spaceship

$x <=> $y

Returns an integer less than, equal to, or greater than zero, depending on if $x is less than, equal to, or greater than $y. Introduced in PHP 7.

 

EXAMPLE:-

<html>

  

   <head>

      <title>Comparison Operators</title>

   </head>

  

   <body>

     

      <?php

         $a = 42;

         $b = 20;

     

         if( $a == $b ) {

            echo "TEST1 : a is equal to b<br/>";

         }else {

            echo "TEST1 : a is not equal to b<br/>";

         }

     

         if( $a > $b ) {

            echo "TEST2 : a is greater than  b<br/>";

         }else {

            echo "TEST2 : a is not greater than b<br/>";

         }

     

         if( $a < $b ) {

            echo "TEST3 : a is less than  b<br/>";

         }else {

            echo "TEST3 : a is not less than b<br/>";

         }

     

         if( $a != $b ) {

            echo "TEST4 : a is not equal to b<br/>";

         }else {

            echo "TEST4 : a is equal to b<br/>";

         }

     

         if( $a >= $b ) {

            echo "TEST5 : a is either greater than or equal to b<br/>";

         }else {

            echo "TEST5 : a is neither greater than nor equal to b<br/>";

         }

     

         if( $a <= $b ) {

            echo "TEST6 : a is either less than or equal to b<br/>";

         }else {

            echo "TEST6 : a is neither less than nor equal to b<br/>";

         }

      ?>

     

   </body>

</html>

 

OUTPUT:-

TEST1 : a is not equal to b

TEST2 : a is greater than b

TEST3 : a is not less than b

TEST4 : a is not equal to b

TEST5 : a is either greater than or equal to b

TEST6 : a is neither less than nor equal to b

====================================================================

5.     Spaceship Operators (Introduced in PHP 7)

PHP 7 introduced this operator called spaceship operator (). These operators are used to compare values and return boolean result, it returns integer values. If both the operands are equal, it returns 0. If the right operand is greater then it returns -1. If the left operand is greater then it returns 1. The following table shows how it works in detail:

OPERATOR

SYNTAX

OPERATION

$x < $y

$x <=> $y

Identical to -1 (right is greater)

$x > $y

$x <=> $y

Identical to 1 (left is greater)

$x <= $y

$x <=> $y

Identical to -1 (right is greater) or identical to 0 (if both are equal)

$x >= $y

$x <=> $y

Identical to 1 (if left is greater) or identical to 0 (if both are equal)

$x == $y

$x <=> $y

Identical to 0 (both are equal)

$x != $y

$x <=> $y

Not Identical to 0

 

Example:

 

<?php

  

$x = 50;

$y = 50;

$z = 25;

  

echo $x <=> $y;

echo "\n";

  

echo $x <=> $z;

echo "\n";

  

echo $z <=> $y;

echo "\n";

  

// We can do the same for Strings

$x = "Ram";

$y = "Krishna";

  

echo $x <=> $y;

echo "\n";

  

echo $x <=> $y;

echo "\n";

  

echo $y <=> $x;

  

?>

 

Output:

0

1

-1

1

1

-1

 

======================================================================

 

6.     PHP Logical Operators

The PHP logical operators are used to combine conditional statements.

Operator

Name

Example

Result

and

And

$x and $y

True if both $x and $y are true

or

Or

$x or $y

True if either $x or $y is true

xor

Xor

$x xor $y

True if either $x or $y is true, but not both

&&

And

$x && $y

True if both $x and $y are true

||

Or

$x || $y

True if either $x or $y is true

!

Not

!$x

True if $x is not true

 

TRUTH TABLE

VALUE 1

VALUE 2

AND

OR

XOR

0

0

0

0

0

0

1

0

1

1

1

0

0

1

1

1

1

1

1

0

 

VALUES

NOT

0

1

1

0

 

 

EXAMPLE:-

<html>

  

   <head>

      <title>Logical Operators</title>

   </head>

  

   <body>

     

      <?php

         $a = 42;

         $b = 0;

        

         if( $a && $b ) {

            echo "TEST1 : Both a and b are true<br/>";

         }else{

            echo "TEST1 : Either a or b is false<br/>";

         }

        

         if( $a and $b ) {

            echo "TEST2 : Both a and b are true<br/>";

         }else{

            echo "TEST2 : Either a or b is false<br/>";

         }

        

         if( $a || $b ) {

            echo "TEST3 : Either a or b is true<br/>";

         }else{

            echo "TEST3 : Both a and b are false<br/>";

         }

        

         if( $a or $b ) {

            echo "TEST4 : Either a or b is true<br/>";

         }else {

            echo "TEST4 : Both a and b are false<br/>";

         }

        

         $a = 10;

         $b = 20;

        

         if( $a ) {

            echo "TEST5 : a is true <br/>";

         }else {

            echo "TEST5 : a  is false<br/>";

         }

        

         if( $b ) {

            echo "TEST6 : b is true <br/>";

         }else {

            echo "TEST6 : b  is false<br/>";

         }

        

         if( !$a ) {

            echo "TEST7 : a is true <br/>";

         }else {

            echo "TEST7 : a  is false<br/>";

         }

        

         if( !$b ) {

            echo "TEST8 : b is true <br/>";

         }else {

            echo "TEST8 : b  is false<br/>";

         }

      ?>

     

   </body>

</html>

 

OUTPUTS  −

TEST1 : Either a or b is false

TEST2 : Either a or b is false

TEST3 : Either a or b is true

TEST4 : Either a or b is true

TEST5 : a is true

TEST6 : b is true

TEST7 : a is false

TEST8 : b is false

 

=====================================================================

7.     PHP String Operators

PHP has two operators that are specially designed for strings.

Operator

Name

Example

Result

.

Concatenation

$txt1 . $txt2

Concatenation of $txt1 and $txt2

.=

Concatenation assignment

$txt1 .= $txt2

Appends $txt2 to $txt1

 

Example:-

<?php

 

$x = "\r\nwelcome  ";

$y = "in  ";

$z = "sjkpgm!!!  ";

echo $x . $y . $z, "\r\n";

echo nl2br("\n");

$x .= $y . $z;

            //echo $x . $y . $z;

echo $x;

 

?>

Output:-

welcome in sjkpgm!!!
welcome in sjkpgm!!!

 

===================================================================

 

8.     PHP Array Operators

The PHP array operators are used to compare arrays.

Operator

Name

Example

Result

+

Union

$x + $y

Union of $x and $y

==

Equality

$x == $y

Returns true if $x and $y have the same key/value pairs

===

Identity

$x === $y

Returns true if $x and $y have the same key/value pairs in the same order and of the same types

!=

Inequality

$x != $y

Returns true if $x is not equal to $y

<> 

Inequality

$x <> $y

Returns true if $x is not equal to $y

!==

Non-identity

$x !== $y

Returns true if $x is not identical to $y

 

Example:

 

<?php

 

$x = array("k" => "Car", "l" => "Bike");

$y = array("a" => "Train", "b" => "Plane");

 echo nl2br("\n");

var_dump ($x + $y);

            echo nl2br("\n");

var_dump($x == $y);

            echo nl2br("\n");

var_dump($x != $y);

            echo nl2br("\n");

var_dump($x <> $y);

            echo nl2br("\n");

var_dump($x === $y);

            echo nl2br("\n");

var_dump($x !== $y);

 

?>

Output:

array(4) {

  ["k"]=>

  string(3) "Car"

  ["l"]=>

  string(4) "Bike"

  ["a"]=>

  string(5) "Train"

  ["b"]=>

  string(5) "Plane"

}

bool(false)

bool(true)

bool(true)

bool(false)

bool(true)

=================================================================== 

9.     Conditional or Ternary Operators

These operators are used to compare two values and take either of the results simultaneously, depending on whether the outcome is TRUE or FALSE. it works as if…else statement.

Syntax:

$var = (condition)? value1 : value2;

Here, the condition will either evaluate as true or false. If the condition evaluates to True, then value1 will be assigned to the variable $var otherwise value2 will be assigned to it.

 

OPERATOR

NAME

OPERATION

?:

Ternary

If the condition is true? then $x : or else $y. This means that if the condition is true then the left result of the colon is accepted otherwise the result is on right.

 

Example:

 

<?php

  $x = -12;

  echo ($x > 0) ? 'The number is positive' : 'The number is negative';

  ?>

 

Output:

The number is negative.

 

EXAMPLE:-

<html>

      <head>

      <title>Arithmetical Operators</title>

   </head>

      <body>

         <?php

         $a = 10;

         $b = 20;

                /* If condition is true then assign a to result otheriwse b */

         $result = ($a > $b ) ? $a : $b;

                  echo "TEST1 : Value of result is $result<br/>";

                  /* If condition is true then assign a to result otheriwse b */

         $result = ($a < $b ) ? $a :$b;

                  echo "TEST2 : Value of result is $result<br/>";

      ?>

      </body>

</html>

 

OUTPUT −

TEST1 : Value of result is 20

TEST2 : Value of result is 10

 

==================================================================

10.           Bitwise operator

The Bitwise operators are used for bit-level operations on the operands. The operators are first converted to bit-level and then the calculation is performed on the operands.

The mathematical operations such as addition, subtraction, multiplication, etc. can be performed at bit-level for faster processing.

Bitwise operators are :-

Description

Operator

Name

Example

Result

&

And

$x & $y

Bits that are set in both $x and $y are set.

|

Or

$x | $y

Bits that are set in either $x or $y are set.

^

Xor

$x ^ $y

Bits that are set in $x or $y but not both are set.

~

Not

~$x

Bits that are set in $x are not set, and vice versa.

<< 

Shift left

$x << $y

Shift the bits of $x $y steps to the left.#

>> 

Shift right

$x >> $y

Shift the bits of $x $y steps to the right.*

 

Concept of bit:-

A bit (Binary digit) is the basic unit of information stored in two states, as ON or OFF. ON state represented by 1 and OFF state represented by 0. these digits are used by BINARY number system which base of 2.

In decimal number system, a number construct upon the base of 10.

Conversion to decimal from binary number -

1011010=(1 x 26)+(0 x 25)+(1 x 24)+(1 x 23)+(0 x 22)+(1 x 21)+(0 x 20)
          =(1 x 64) +(0 x 32)+(1 x 16)+(1 x 8)+(0 x 4)+(1 x 2)+(0 x 1)
          =64+0+16+8+0+2+0
          =90

So, (1011010)2= (90)10 

------------------------------------------------------------------------------------------------------------

Byte

A byte is a sequence of eight bits. The maximum value of a byte is 255.

 

Table show of a byte:-

 

1 Byte ( 8 bits )

Place Value

128

64

32

16

8

4

2

1

 

 

 

1

1

1

1

1

1

1

1

 

 

 

27

26

25

24

23

22

21

20

 

 

 

128

64

32

16

8

4

2

1

=

255

 

A decimal number 93 can be represented in binary form like bellow –

 

1 Byte ( 8 bits )

Place Value

128

64

32

16

8

4

2

1

 

 

 

0

1

0

1

1

1

0

1

 

 

 

27

26

25

24

23

22

21

20

 

 

 

0

64

0

16

8

4

0

1

=

93

-----------------------------------------------------------------------------------------------------------  

Bitwise AND (&)

According to the truth table:-

 

TRUTH TABLE

VALUE 1

VALUE 2

AND

0

0

0

0

1

0

1

0

0

1

1

1

 

Example of PHP bitwise AND with one shared bit

<?php

$x=13;

$y=22;

echo $x & $y;

?>


Output of the example 

4

Explanation

 

1 Byte ( 8 bits )

Place Value

128

64

32

16

8

4

2

1

 

 

$x

0

0

0

0

1

1

0

1

=

13

$y

0

0

0

1

0

1

1

0

=

22

$x & $y

0

0

0

0

0

1

0

0

=

04

 

Bitwise OR ( | )

According to the truth table

TRUTH TABLE

VALUE 1

VALUE 2

OR

0

0

0

0

1

1

1

0

1

1

1

1

 

Example of PHP bitwise OR

1 Byte ( 8 bits )

Place Value

128

64

32

16

8

4

2

1

 

 

$x

0

0

0

0

0

1

0

1

=

5

$y

0

0

0

0

1

0

1

1

=

11

$x & $y

0

0

0

0

1

1

1

1

=

15

 

<?php

$x=5;

$y=11;

echo $x | $y;

?>


Output

15


Explanation

Bitwise XOR (^)

The Xor operator also performs a bitwise comparison in two numeric expressions and sets the corresponding bit in the result. When one and only one of the expressions evaluates to true the result is true.

 

TRUTH TABLE

VALUE 1

VALUE 2

XOR

0

0

0

0

1

1

1

0

1

1

1

0

 

The below table shows how a XOR operation performs.

Expression1

Expression2

Result

False

False

False

False

True

True

True

False

True

True

True

False

 

Example of PHP bitwise XOR

<?php

$x=12;

$y=11;

echo $x ^ $y;

?>


Output

7

 

Explanation

 

1 Byte ( 8 bits )

Place Value

128

64

32

16

8

4

2

1

 

 

$x

0

0

0

0

1

1

0

0

=

12

$y

0

0

0

0

1

0

1

1

=

11

$x ^ $y

0

0

0

0

0

1

1

1

=

07

 

Bitwise NOT

The below table will display how NOT operator performs on $x and $y and returns true when a set bit of one expression is not set in another expression.

Example of PHP bitwise NOT using after AND

<?php

$x=12;

$y=10;

echo $x & ~ $y;

?>


Output

4

 

Explanation

1 Byte ( 8 bits )

Place Value

128

64

32

16

8

4

2

1

 

 

$x

0

0

0

0

1

1

0

0

=

12

$y

0

0

0

0

1

0

1

0

=

10

~$y

0

0

0

0

0

1

0

1

=

05

$x & ~$y

0

0

0

0

0

1

0

0

=

04

 

Example of PHP bitwise NOT using before AND<?php

$x=12;

$y=10;

echo ~ $x &  $y;

?>


Output

2

 

Bit Shifting

If a and b are two numbers, BIT SHIFTING shifts a bits b number of steps. each step refers to multiply by two if it is BIT SHIFT LEFT. If it is BIT SHIFT RIGHT, then each step refers to division by two.

Example of PHP Bit Shifting ( left shift )<?php

$x=8;

$y=3;

echo $x << $y;

?>

 

Output

64

 

Explanation

1 Byte ( 8 bits )

Place Value

128

64

32

16

8

4

2

1

 

 

$x

0

0

0

0

1

0

0

0

=

8

Output

0

1

0

0

0

0

0

0

=

64

 

In this example, the value of $x that is 8 is taken and a BIT SHIFT LEFT operation is performed. So, 8 is multiplied by 2 thrice. Thus we get 8 x 2 x 2 x 2 = 64.

 

 

Example of PHP Bit Shifting ( right shift )

<?php

$x=8;

$y=3;

echo $x >> $y;

?>

 

Output

1

 

Explanation

1 Byte ( 8 bits )

Place Value

128

64

32

16

8

4

2

1

 

 

$x

0

0

0

0

1

0

0

0

=

8

Output

0

0

0

0

0

0

0

1

=

1

In the above example, a value of $x that is 8 is taken and a BIT SHIFT RIGHT operation is performed. So, 8 is divided by 2 three times. Thus we get 8/2=4/2=2/2 = 1.

Example:-

<?php

    // PHP code to demonstrate Bitwise Operator.

          

    // Bitwise AND

    $First = 5;

    $second = 3;

    $answer = $First & $second;

      

    print_r("Bitwise & of 5 and 3 is $answer");

      

    print_r("\n");

      

    // Bitwise OR

    $answer = $First | $second;

    print_r("Bitwise | of 5 and 3 is $answer");

      

    print_r("\n");

      

    // Bitwise XOR

    $answer = $First ^ $second;

    print_r("Bitwise ^ of 5 and 3 is $answer");

      

    print_r("\n");

      

    // Bitwise NOT

    $answer = ~$First;

    print_r("Bitwise ~ of 5 is $answer");

      

    print_r("\n");

      

    // Bitwise Left shift

    $second = 1;

    $answer = $First << $second;

    print_r("5 << 1 will be $answer");

      

    print_r("\n");

      

    // Bitwise Right shift

    $answer = $First >> $second;

    print_r("5 >> 1 will be $answer");

      

    print_r("\n");

?>

Output:

Bitwise & of 5 and 3 is 1

Bitwise | of 5 and 3 is 7

Bitwise ^ of 5 and 3 is 6

Bitwise ~ of 5 is -6

5 << 1 will be 10

5 >> 1 will be 2

 

 

==================================================================

Precedence of PHP Operators

the highest precedence appears at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Category

Operator

Associativity

Unary

! ++ --

Right to left

Multiplicative

* / %

Left to right

Additive

+ -

Left to right

Relational

< <= > >=

Left to right

Equality

== !=

Left to right

Logical AND

&&

Left to right

Logical OR

||

Left to right

Conditional

?:

Right to left

Assignment

= += -= *= /= %=

Right to left

 

======================================================================

Type Operators

The type operator instanceof is used to determine whether an object, its parent, and its derived class are the same type or not. Basically, this operator determines which certain class the object belongs to. It is used in object-oriented programming.

<?php  

    //class declaration  

    class Developer  

    {}  

    class Programmer  

    {}  

    //creating an object of type Developer  

    $charu = new Developer();  

      

    //testing the type of object  

    if( $charu instanceof Developer)  

    {  

        echo "Charu is a developer.";  

    }  

    else  

    {     

        echo "Charu is a programmer.";  

    }  

    echo "</br>";  

    var_dump($charu instanceof Developer);           //It will return true.  

    var_dump($charu instanceof Programmer);       //It will return false.  

?>  

Output:

Charu is a developer.

bool(true) bool(false)

 

======================================================================

Error Control Operators

PHP has one error control operator, i.e., at (@) symbol. Whenever it is used with an expression, any error message will be ignored or hidden that might be generated by that expression.

 

Operator

Name

Example

Explanation

@

at

@file ('non_existent_file')

Intentional file error

 

=============================

Post a Comment

0 Comments