PHP Operators

PHP Operators

PHP Operator is a symbol that performs operations on operands.

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


Operators Categories

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

  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.


OPERATORNAMESYNTAXOPERATION
++Pre-Increment++$xFirst increments $x by one, then return $x
Pre-Decrement–$xFirst 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 Decrement first then Assign

1

2 Assign first then decrements

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

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.


OperatorNameExampleResult
+Addition$x + $ySum of $x and $y
-Subtraction$x - $yDifference of $x and $y
*Multiplication$x * $yProduct of $x and $y
/Division$x / $yQuotient of $x and $y
%Modulus$x % $yRemainder of $x divided by $y
**Exponentiation$x ** $yResult 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

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

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.


AssignmentSame as...Description
x = yx = yThe left operand gets set to the value of the expression on the right
x += yx = x + yAddition
x -= yx = x - ySubtraction
x *= yx = x * yMultiplication
x /= yx = x / yDivision
x %= yx = x % yModulus

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

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

PHP Comparison Operators

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


OperatorNameExampleResult
==Equal$x == $yReturns true if $x is equal to $y
===Identical$x === $yReturns true if $x is equal to $y, and they are of the same type
!=Not equal$x != $yReturns true if $x is not equal to $y
<> Not equal$x <> $yReturns true if $x is not equal to $y
!==Not identical$x !== $yReturns true if $x is not equal to $y, or they are not of the same type
Greater than$x > $yReturns true if $x is greater than $y
Less than$x < $yReturns true if $x is less than $y
>=Greater than or equal to$x >= $yReturns true if $x is greater than or equal to $y
<=Less than or equal to$x <= $yReturns true if $x is less than or equal to $y
<=>Spaceship$x <=> $yReturns 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

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

Spaceship Operators (Introduced in PHP 7)

PHP 7 introduced this operator called spaceship operator (). 

These operators are used to compare values and return a 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:


OPERATORSYNTAXOPERATION
$x < $y$x <=> $yIdentical to -1 (right is greater)
$x > $y$x <=> $yIdentical to 1 (left is greater)
$x <= $y$x <=> $yIdentical to -1 (right is greater) or identical to 0 (if both are equal)
$x >= $y$x <=> $yIdentical to 1 (if left is greater) or identical to 0 (if both are equal)
$x == $y$x <=> $yIdentical to 0 (both are equal)
$x != $y$x <=> $yNot 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

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

PHP Logical Operators

The PHP logical operators are used to combine conditional statements.


OperatorNameExampleResult
andAnd$x and $yTrue if both $x and $y are true
orOr$x or $yTrue if either $x or $y is true
xorXor$x xor $yTrue if either $x or $y is true, but not both
&&And$x && $yTrue if both $x and $y are true
||Or$x || $yTrue if either $x or $y is true
!Not!$xTrue if $x is not true

TRUTH TABLE


VALUE 1VALUE 2ANDORXOR
00000
01011
10011
11110

VALUESNOT
01
10

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

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

PHP String Operators

PHP has two operators that are specially designed for strings.


OperatorNameExampleResult
.Concatenation$txt1 . $txt2Concatenation of $txt1 and $txt2
.=Concatenation assignment$txt1 .= $txt2Appends $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!!!

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

PHP Array Operators

The PHP array operators are used to compare arrays.


OperatorNameExampleResult
+Union$x + $yUnion of $x and $y
==Equality$x == $yReturns true if $x and $y have the same key/value pairs
===Identity$x === $yReturns true if $x and $y have the same key/value pairs in the same order and of the same types
!=Inequality$x != $yReturns true if $x is not equal to $y
<> Inequality$x <> $yReturns true if $x is not equal to $y
!==Non-identity$x !== $yReturns 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)

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

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.


OPERATORNAMEOPERATION
?:TernaryIf the condition is true? then $x : or else $y. This means that if the condition is true then the left the result of the colon is accepted otherwise the result 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

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

 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


OperatorNameExampleResult
&And$x & $yBits that are set in both $x and $y are set.
|Or$x | $yBits that are set in either $x or $y are set.
^Xor$x ^ $yBits that are set in $x or $y but not both are set.
~Not~$xBits that are set in $x are not set, and vice versa.
<< Shift left$x << $yShift the bits of $x $y steps to the left.#
>> Shift right$x >> $yShift the bits of $x $y steps to the right.*

Bitwise AND (&)

According to the truth table:-


TRUTH TABLE


VALUE 1VALUE 2AND
000
010
100
111

Example of PHP bitwise AND with one shared bit

<?php
$x=13;
$y=22;
echo $x & $y;
?>

The output of the example 

4

Explanation


1 Byte ( 8 bits )
Place Value1286432168421  
$x00001101=13
$y00010110=22
$x & $y00000100=04

In the above table, the value set for $x(13) in the 1st, 3rd, and 4th place. The place value respectively is 1,4 and 8 and the value set for $y(22) in the 2nd, 3rd, and 5th place with the corresponding place value 2, 4, and 16.

$x and $y answer is  4 is returned


Example of PHP bitwise AND with two shared bit

<?php
$x=77;
$y=198;
echo $x & $y;
?>

Output

68

Explanation


1 Byte ( 8 bits )
Place Value1286432168421  
$x01001101=77
$y11000110=198
$x & $y01000100=68

In the above table, the value set for $x(77) in the 1st, 3rd, 4th, and 7th place. The place values are 1, 4, 8, and 64, and the value set for $y(198) in the 2nd, 3rd, 7th, and 8th place with the corresponding place values 2, 4, 64, and 128.

The answer of this   3rd and 7th bits. So 64 + 4 = 68 returns.


Bitwise OR ( | )

According to the truth table

TRUTH TABLE


VALUE 1VALUE 2OR
000
011
101
111

Example of PHP bitwise OR

<?php
$x=5;
$y=11;
echo $x | $y;
?>

Output

15

Explanation


1 Byte ( 8 bits )
Place Value1286432168421  
$x00000101=5
$y00001011=11
$x & $y00001111=15

In the above table, the value set for $x(5) in the 1st and 3rd place. The place value respectively is 1 and 4, and the value set for $y(11) in the 1st, 2nd, and 4th place with the corresponding place value 1, 2, and 8.

the table shows that the $x and $y sets together either 1st or 2nd or 3rd or 4th bits. So return value is the addition of place value of the sets bits, that is 8+4+2+1=15.


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 1VALUE 2XOR
000
011
101
110

The below table shows how an XOR operation performs.


Expression1Expression2Result
FalseFalseFalse
FalseTrueTrue
TrueFalseTrue
TrueTrueFalse

Example of PHP bitwise XOR

<?php
$x=12;
$y=11;
echo $x ^ $y;
?>

Output

7

Explanation


1 Byte ( 8 bits )
Place Value1286432168421  
$x00001100=12
$y00001011=11
$x ^ $y00000111=07

In the above table, the value set for $x(12) in the 3rd and 4th place. The place value respectively is 4 and 8, and the value sets for $y(11) in the 1st, 2nd, and 4th place with the corresponding place value 1, 2, and 8.

the $x and $y sets together either 1st or 2nd or 3rd or 4th bits but they shared together only a 4th bit. So, return value is the addition of place value of the set bits but not the bit shared together, that is 4+2+1=7.


Bitwise NOT

The below table will display how the 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 Value1286432168421  
$x00001100=12
$y00001010=10
~$y00000101=05
$x & ~$y00000100=04

In the above table, the value set for $x(12) in the 3rd and 4th place. The place value respectively is 4 and 8, and the value sets for $y(10) in the 2nd and 4th place with the corresponding place value 2 and 8.

So you can see from the above table that, the $x and $y sets together either 1st or 2nd or 3rd or 4th bits but they shared together only a 4th bit. So return value is the 4, because of only bit sets in $x but not in $y.

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 Value1286432168421  
$x00001000=8
Output01000000=64

In the above 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.

Advance example of PHP Bit Shifting ( left shift )

<?php
$x=12;
$y=4;
echo  $x << $y;
?>

Output

192

Explanation

In the above example, a value of $x that is 12 is taken and a BIT SHIFT LEFT operation is performed. So, 12 is multiplied by 2 four times. Thus we get 12 x 2 x 2 x 2 x 2 = 192.


1 Byte ( 8 bits )
Place Value1286432168421  
$x00001100=12
Output11000000=192

Example of PHP Bit Shifting ( right shift )

<?php
$x=8;
$y=3;
echo $x >> $y;
?>

Output

1

Explanation


1 Byte ( 8 bits )
Place Value1286432168421  
$x00001000=8
Output00000001=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.

Advance example of PHP Bit Shifting ( right shift )

<?php
$x=96;
$y=5;
echo  $x >> $y;
?>

Output

3

Explanation


1 Byte ( 8 bits )
Place Value1286432168421  
$x01100000=96
Output00000011=3

In the above example, a value of $x that is 96 is taken and a BIT SHIFT RIGHT operation is performed. So, 96 is divided by 2 five times. Thus we get 96/2=48/2=24/2=12/2=6/2= 3.

Example of PHP Bit Shifting ( right shift ) exceeds step value

<?php
$x=64;
$y=7;
echo  $x >> $y; 
?>

Output

0

Explanation


1 Byte ( 8 bits )
Place Value1286432168421  
$x01000000=64
Output00000000=0

In the above example, a value of $x that is 64 is taken and a BIT SHIFT RIGHT operation is performed. So, 64 is divided by 2 seven times. While dividing at a certain point we don't have anything left to divide. Thus the return is 0.

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

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


Post a Comment

0 Comments