PHP Operator’s

0
1865

In this PHP Operators tutorial we will study about operators in PHP and how they are used in expressions.

  • What are operators?
  • Operators are the entities in any language that are used to perform different operations like arithmetic, logical, comparison etc. in any given expression.

  • Terms related to operators:
  • Some terms related to operators are:

    • Operands: Operands are the numbers or variables containing values on which the operator performs operation.
      • For example: 5+2;
      • In the above example 5 and 2 are the operands and + is the arithmetic addition operator which performs addition of 5 and 2 and outputs result as 7.
    • Expression: Expression is any combination of constants, variables and operators that evaluate to certain value as per the precedence of the operator which is stored in another or same variable.
      • For example:

      • In the above example the value of expression a+b-2 will be evaluated to 13 and stored in variable z due to the assignment operator. Work of assignment operator is to assign its right hand side value to its left hand side variable.
    • Precedence: Precedence or Associativity of an operator is the ability given to operators to decide which operation to perform first in an expression.
      For example: in the above example, expression $z=$a+$b-2; is evaluated from left to right i.e. first preference is given to + operator and addition of $a and $b is performed. Then subtraction is performed using – operator with the value evaluated by addition and 2. Then the result is assigned to variable $z.
  • Types of operators:
  • Operators are classified according to the number of operands used with it.

    1. Unary operators:
      • The operators used with only one operand are called unary operators.
      • For example:
      • Here, in the above example, $a is an operand and ++ is the increment operator. Its function is to increment the value of $a by one i.e. make it 11.
    2. Binary operators:
      • The operators used with two operands are called binary operators.
      • For example: 7+4
      • Here the + operator has two operands 7 and 4.
    3. Ternary operators:
      • Operators used with three operators are called ternary operators.
      • Example of ternary operator is ?:. It is also called as conditional operator.
      • For example:
      • Here, if the expression is true i.e. If 10 is less than 20 then the expression or value after question mark (?) will be evaluated otherwise the expression or value after colon (:) will be evaluated. In the case of above example value evaluated will be true since 10 is less than 20 as stated in the expression.
  • Various operator’s:
  • Let us see different operators used in PHP for different tasks.

    1. Arithmetic operators:
      • Arithmetic operators operate on integers and floats. If any operand is not of correct type, it is converted to one i.e. integer or float and then evaluated.
      • The arithmetic operators are listed in the table below:
      • Name Operator Example Description
        Addition + $x+$y Sum of $x and $y
        Subtraction $x-$y Subtraction of $x and $y
        Multiplication * $x*$y Multiplication of $x and $y
        Division / $x/$y Divide $x and $y & obtain its quotient
        Modulus % $x%$y Divide $x and $y & obtain its remainder
      • For demonstration of the operator’s create a new folder named operators in the htdocs folder in xampp folder in C drive. Create a new file named index.php in this newly created operators folder.
      • • Write the following code in index.php to demonstrate arithmetic operators:

      • The output is shown below:
      • arithmetic_operators_output
        fig 1

      • In the above output you can see that addition, subtraction, multiplication, division and modulus operations are done.
      • The +, – and * operators perform straight forward addition, subtraction and multiplication.
      • But in division we can use 2 operators. If we require quotient by dividing 2 numbers we need to use division (/) operator. As shown in the figure above the division of 30 by 10 using / operator gives its quotient which is 3.
      • Similarly if we require remainder by dividing 2 numbers, we need to use modulus (%) operator. As shown in the figure above the division of 30 by 10 using % operator gives its remainder which is 0 since 30 is completely divisible by 10.
    2. Assignment operators:
      • Assignment operators are used to assign values to variables. I mean the right side value is set to the left side variable or expression.
      • These values may in turn assigned to another variables or expressions.
      • Assignment operators can also be used with arithmetic operators.
      • The various assignment operators are listed in the table below:
      • Name Operator Example Description
        Assignment = $x=10; Assigning value 10 to $x variable.
        Addition Assignment += $x+=10; It is similar to $x = $x + 10 i.e. value 10 is added to the value of $x and stored in $x itself.
        Subtraction Assignment -= $x-=10; It is similar to $x = $x – 10 i.e. value 10 is subtracted from value of $x and stored in $x itself.
        Multiplication Assignment *= $x*=10; It is similar to $x = $x * 10 i.e. value 10 is multiplied to value of $x and stored in $x itself.
        Division Assignment /= $x/=10; It is similar to $x = $x / 10 i.e. value in $x variable is divided by 10 and the quotient obtained is stored in $x itself.
        Modulus Assignment %= $x%=10; It is similar to $x = $x % 10 i.e. value in $x variable is divided by 10 and the remainder obtained is stored in $x itself.
      • Write the following code in index.php to demonstrate assignment operators:
      • The output is shown below:
      • assignment_operators_output
        fig 2

      • In the above code you can see that the values calculated are assigned to the same variable.
      • We can use these assignment operators in all operations.
    3. String operators:
      • There are special two operators used with strings.
      • These operators are listed in the table below:
      • Name Operator Example Description
        Concatenation . $str=”Sharlet”.”D’Souza” The string “Sharlet” is concatenated to the string “D’souza” using period (.) which is known as concatenation operator. Hence $str variable will now contain the value “Shartlet D’souza”.
        Concatenation Assignment .= $str=”Good”;
        $str.=”Morning”;
        Here the variable $str already contains a string “Good”. In the next statement of code it is concatenated with the string “Morning” using concatenation assignment operator (.=). Hence the result will be $str=”Good Morning”.
      • Write the following code in index.php to demonstrate string operators:
      • The output is shown below:
      • string_assignment_operators_output
        fig 3

      • We have explained the same examples as given in table above.
      • Here, strings “Sharlet” and “ D’souza” are concatenated using a concatenation operator period (.) and stored in a variable $str.
      • Next a variable $str1 contains a string “Good”. It is later concatenated to the string “Morning” using the concatenation assignment operator (.=) and then the whole string “Good Morning” is stored in variable $str1.
    4. Comparison operators:
      • Comparison operators are used to compare two constants, values of two variables or expressions.
      • These are mostly used in conditional statements or decision making statements.
      • These operators always evaluate to a Boolean value i.e. true or false.
      • The comparison operators are listed in the table below:
      • Name Operator Example Description
        Equal == $x==$y; It returns true if value in $x is equal to value in $y.
        Identical === $x===10; It returns true if value in $x is equal to value in $y and they both are of same type.
        Not Equal != $x!=$y; It returns true if value in $x is not equal to value in $y.
        Not Equal <> $x<>$y; It returns true if value in $x is not equal to value in $y.
        Not Identical !== $x!==$y; It returns true if value in $x is not equal to value in $y or they both are not of same type.
        Greater than > $x>$y; It returns true if value in $x is greater than the value in $y.
        Less than < $x<$y; It returns true if value in $x is less than the value in $y.
        Greater than or equal to >= $x>=$y; It returns true if value in $x is greater than or equal to the value in $y.
        Less than or equal to <= $x<=$y; It returns true if value in $x is less than or equal to the value in $y.
      • Write the following code in index.php to demonstrate comparison operators:
      • The output is shown below:
      • comparison_operators_output
        fig 4

      • In the above code we have used if—else conditional statements to check the comparison operators. Don’t worry about the conditional statement (if — else), we will study it in detail in next coming chapters. You just focus on the values obtained after comparing the variables with different comparison operator.
      • In the output you will see that the identical comparison operator checks for the value as well as the data type of the variables. It will declare is not identical even if one thing does not match.
      • The difference in equal and identical is only this that equal tries to match only values and identical tries to match values as well as data types.
      • There is one more comparison operator which is not stated above. It is ternary comparison operator.
      • The ?: is a ternary comparison operator or it is also called as conditional comparison operator.
      • It is called as ternary because it has 3 operands.
      • Syntax of ternary comparison operator is as follows:
      • The Expression1 is any condition checked or any expression. If this expression evaluates to true then the expression following the question mark (?) is evaluated otherwise the expression followed by colon (:) is evaluated.
      • It is mostly used to take decisions in a one line code.
      • Example:
      • Here, in the above example the condition (10>20) is not true hence the expression/statement after colon (:) will be evaluated i.e. it will return false output.
      • But if the condition would have been (20>10) then the answer would be true, because if the condition is satisfying then the statement/expression after question mark (?) is evaluated.
      • Let us see output of the following use of ternary operator. Write the following code in index.php file:
      • Here we have a variable $age with age 20.
      • We check if the age is greater than or equal to 18 in expression1 of ternary operator. In this case the age 20 is greater than 18, hence the expression has evaluated to true. Since the expression has evaluated to true, the expression 2 which comes after question mark (?) gets evaluated and the value is stored in variable $v.
      • This value is then equated with 1 because 1 represents true and 0 represents false.
      • As our expression has been evaluated to true, the echo statement under if is executed and we get the output as You are eligible for voting.
      • ternary_comparison_operator_output
        fig 5

      • If the expression might have been evaluated to false, the output would have been You are not eligible for voting.
    5. Logical operators:
      • Logical operators are used to compare the results of two expressions.
      • The operators are listed in the table below:
      • Name Operator Example Description
        Logical And and $x and $y; The expression evaluates to true if both $x and $y are true.
        Logical Or or $x or $y; The expression evaluates to true even if one expression among $x or $y are true.
        Logical Xor xor $x xor $y; The expression evaluates to true if one expression among $x or $y are true, but it evaluates to false if both $x and $y are true.
        Logical And && $x && $y; The expression evaluates to true if both $x and $y are true.
        Logical Or || $x || $y; The expression evaluates to true even if one expression among $x or $y are true.
        Logical Not ! !$x It is true if $x is not true
      • Write the following code in index.php to demonstrate logical operators:
      • The output is shown below:
      • logical_operators_output
        fig 6

      • We have shown some examples of the logical operators.
      • In the code given for and logical operator the expressions ($a==40) and ($b==($a*1)) both evaluate to true, hence the output is true.
      • Similarly in the expression for or logical operator the expression ($c<$d) is true and the expression ($d<$c) is false. In or operation either of the expression should be true. In or operation the expressions are checked from left side. If the left expression is true it evaluates to true immediately. It doesn’t even check the right side expression.
      • For not logical operator the not operator (!) makes the value negative and evaluates to true when the value of expression is false.
    6. Increment/Decrement operators:
      • Increment and Decrement operators are used to increment or decrement the values of the operands by one.
      • The increment /decrement operators are listed in the table given below:
      • Operator Name Example Description
        ++ Pre-increment ++$x It increments the value of $x by 1 first and then returns its value.
        Post-increment $x++ It returns the value of $x first and then increments it by 1.
        Pre-decrement –$x It decrements the value of $x by 1 first and then returns its value.
        Post-decrement $x– It returns the value of $x first and then decrements it by 1.
      • Write the following code in index.php to demonstrate increment/decrement operators:
      • The output is shown below:
      • incre_decre_operators
        fig 7

      • Here, in the above output it is totally clear that,
        1. When you use pre-increment operator i.e. when you use the increment operator before the operand or expression, it first increments its value by 1 and then prints is as shown in the case of variable $x.
        2. But when you use post-increment operator i.e. when you use the increment operator after the operand or expression, it first prints its value and then increments it is as shown in the case of variable $y.
        3. When you use pre-decrement operator i.e. when you use the decrement operator before the operand or expression, it first decrements its value by 1 and then prints is as shown in the case of variable $z.
        4. But when you use post-decrement operator i.e. when you use the decrement operator after the operand or expression, it first prints its value and then decrements it is as shown in the case of variable $a.
    7. Bitwise operators:
      • Bitwise operators are used to operate on individual bits of integer values.
      • These operators are not in use often.
      • Bitwise operators operate on the underlying binary representation of the numbers.
      • If it works with a string, it works on character by character basis.
      • The bitwise operators are listed in the table given below:
      • Name Operator Example Description
        And & $x & $y; It returns true if bits of both $x and $y are true.
        Or | $x | $y; It returns true if either bit of the bits of $x and $y are true.
        Not ~ ~$x It returns the bits that are not true in $x.
        Xor ^ $x ^ $y; It returns bits that are true in either $x or $y, but does not return true if both the bits in $x and $y are same.
        Left Shift << $x << $y; It shifts the bits in $x to the left by $y bits.
        Right Shift >> $x >> $y; It shifts the bits in $x to the right by $y bits.
      • Let us see some examples of bitwise operators:
      • Let,

      • $x=3; // 0011
        $y=2; //0010
        $z=1; //0001
        Then,
        i)$a=$x & $y; // it returns 2 (0011) & (0010) = (0010)
        ii)$b=$x|$y; // it returns 3 (0011) | (0010) = (0011)
        iii)$c=$y^$z; // it returns 3 (0010) ^ (0001)= (0011)
        iv)$d=$x << $y // it returns 12 v)$e=$x>>$y // it returns 0

      • In the above given examples we know that internally the values are represented in the form of bits and bitwise operators are used to operate them.
      • We have $x with value 3 which is represented as 0011 in binary format, $y with value 2 which is represented as 0010 in binary format and $z with value 1 which is represented as 0001 in binary format.
      • In bitwise and (&) operation when same position bits are set in both the numbers then that bit is set even in the result.
      • In bitwise or (|) operation when either of the bits or both the bits of the number are set then that bit is set even in the result.
      • In bitwise xor (^) operator when either bits are set in both the numbers then that bit is set in the result. It doesn’t set the bit when both the bits are same as in or operation.
      • In bitwise left shift operation (<<) the bits of first number are shifted to left by the second number of times. It is as simple as multiplying the first number by second the second number times. I mean if the expression is 3<<2, the output will be obtained by 3*2*2=12.
      • In bitwise right shift operation (>>) the bits of first number are shifted to right by the second number of times. It is as simple as dividing the first number by second the second number times. I mean if the expression is 3>>2, the output will be obtained by (3/2)/2=0.
    8. Array operators:
      • Some of the operators seen earlier have different behavior for arrays:
      • The operators are listed in the table below:
      • Name Operator Example Description
        Union + $ar1 + $ar2; It returns the array containing the union of keys from both the arrays (same keys are not repeated).
        Equality == $ar1 == $ar2; It returns true if the key/value pairs of both the arrays is same (order may differ).
        InEquality != $ar1 != $ar2; It returns true if either array has a key/value pair that the other doesn’t have.
        InEquality <> $ar1 <> $ar2; It returns true if either array has a key/value pair that the other doesn’t have.
        Identity === $ar1 === $ar2; It returns true if both the arrays have same key/value pairs in same order.
        Non – Identity !== $ar1 !== $ar2; It returns true if both the arrays don’t have same key/value pairs in same order.
      • Let us see the following examples:
      • If there are 2 arrays as follows:
      • $x=array(10,20,30);
        $y=array(40,50,60);
        Then,
        $a=$x + $y; //will give array(10,20,30)

      • This is because only the keys/indices of two arrays are matched and the values of first array of are captured for the resultant array. It has nothing to do with values, it is focused only on keys of arrays.
      • Next if there are 2 arrays,
      • $a=array(20,30,40);
        $b=array(1 => 30,2 => 40, 0 => 20);
        Then,
        $x=$a == $b; // will return true
        $y=$a === $b; // will return false

      • In the above code the equality expression ($x=$a == $b) returns true because it needs that all the key/value pairs should be same in both the arrays. Order of the key/value pair is not considered.
      • But in the Identity expression ($y=$a === $b) the equality as well as the order of the key/value pair is matched in both the arrays. Hence the result is false.
    9. Other operators:
      • There is an operator (@) which prevents errors to appear.
      • If in a s/w project we are trying to open a file or database connection.
      • If the database connection fails to establish or the file could not be opened, at that time a error message occurs.
      • To suppress this error message are to run our s/w further smoothly at sign (@) sign is used before the statement giving error.
  • Precedence Table:
    • Precedence or Associativity is the most important part to study the working of operators.
    • The operators evaluate the expressions as per the rules of associativity.
    • The Associativity of operators is listed in the table below:
    • Associativity Operators
      n/a new
      right [ (for arrays)
      right ! ~ ++ @ type casts
      left * / %
      left + –
      left << >>
      n/a < <= > >=
      n/a == != <> === !==
      left &
      left ^
      left |
      left &&
      left ||
      left ?:
      right = +== *= /= .= %= &= |= ^= <<= >>=
      right print
      left And
      left Xor
      left or
      left ,
    • The above shown precedence table is very important in the evaluation of expressions.
    • The operators follow the rules of the precedence table.
    • In the above given table, the operators from top to bottom have decreasing precedence i.e. the operators that are on top have high precedence; they are executed first.
    • Next the expression with the given operators is evaluated as specified in the Associativity column.
    • For eg: in the expression,
    • The associativity of arithmetic operators is left to right and that among + and *, multiplication operator has higher precedence than addition operator.
    • So from left to right higher precedence is given to *, so the expression ($y * $z) will evaluate and then ($x + output of ($y * $z)) is evaluated. Then the value is assigned to $a since assignment operator has less precedence and is evaluated from right to left.
    • If we want to purposefully evaluate the expression $x + $y before $y * $z, we can put the expression $x + $y in parenthesis.
    • Since parenthesis has precedence even higher than the multiplication operator, the expression ($x + $y) will be executed first.
    • The above expression with parenthesis can be written like this,

Thus we completed the detailed operators and expressions in this PHP operator’s tutorial.

LEAVE A REPLY

Please enter your comment!
Please enter your name here