06/29/2011

PHP Operators
Share

by Cyle — Categories: php — Tags: , , , Leave a comment

An operator is something that takes one value and yields it with another value to produce a new value or expression. There are many different types of operators used in PHP. Below they are broken into categories.

  • Arithmetic Operators
  • Assignment Operators
  • Bitwise Operators
  • Comparison Operators
  • Error Control Operator
  • Incrementing/Decrementing Operators
  • Logical Operators
  • String Operators
  • Array Operators


    •  

      Arithmetic Operators

      Arithmetic operators are like the basic math operators we all learned in school.

      Example Name Result
      -$a Negation Opposite of $a
      $a + $b Addition Sum of $a and $b
      $a – $b Subtraction Difference of $a and $b
      $a * $b Multiplication Product of $a and $b
      $a / $b Division Quotientof $a and $b
      $a % $b Modulus Remainder of $a divided by $b
      Examples:
      <?php
      echo (5 + 2);	// prints 7
      echo (5 - 1);	// prints 4
      echo (5 * 2);	// prints 10
      echo (5 / 2);	// prints 2.5
      echo (5 % 5);	// prints 0
      echo (5 % 2);	// prints 3
      echo (-5 % -3);	// prints -2 (sign matches dividend)
      echo (5 % -3);	// prints 2 (sign matches dividend)
      ?>
      Practical Use Example:
      <?php
      if(($someNumber%2)==0) {
      	echo 'The number is even.';
      } else {
      	echo 'The number is odd.';
      }
      ?>

      Assignment Operators

      The main assignment operator is “=” (the equals to sign), but it is far more than just equals to! In reality it means that the operand on the left gets set to the value or expression on the right. Notice that $a=5 is 5. We can do some creative things with this idea:

      <?php
      $a = ($b = 5) + 3;
      //$a is now 8, and $b is set to 5
      ?>

      To set a value to a key in an array we use the “=>”. More information on that can be found here. We can also combine other operators with the assignment operators. Examples below:

      <?php
      $a = 5;
      $a += 4;		// same as $a = $a + $4 = 9
      $b = 'Welcome ';
      $b .= 'Home!';		// sets $b to 'Welcome Home!'
      			// same as $b = $b . 'Home!'
      ?>
      Assignment by Reference

      Assignment by reference is when two variables point to the same data, but nothing is copied.

      <?php
      $a = 5;
      $b = &$a;		// $b is now pointing to $a
       
      echo $a;		// prints 5
      echo $b;		// prints 5
       
      $a = 3;			// changing $a changes $b
       
      echo $a;		// prints 3
      echo $b;		// prints 3
      ?>

      Bitwise Operators

      Bitwise operators manipulate specific bits within an integer.

      Example Name Result
      $a & $b And Bits that are set in both $a and $b are set.
      $a | $b Or (inclusive or) Bits that are set in either $a or $b are set.
      $a ^ $b Xor (exclusive or) Bits that are set in $a or $b but not both are set.
      ~ $a Not Bits that are set in $a are not set, and vice versa.
      $a <<< $b Shift left Shift the bits of $a $b steps to the left (each step means “multiply by two”)
      $a >> $b Shift right Shift the bits of $a $b steps to the right (each step means “divide by two”)

      I hardly ever see this being used, so I won’t go into any more detail, but if you want more information visit PHP.net : Bitwise Operators.

      Comparison Operators

      Comparison operators allow you to compare two values.

      Example Name Result
      $a == $b Equal TRUE if $a is equal to $b after type juggling.
      $a === $b Identical TRUE if $a is equal to $b, and they are of the same type.
      $a != $b Not equal TRUE if $a is not equal to $b after type juggling.
      $a <> $b Not equal TRUE if $a is not equal to $b after type juggling.
      $a !== $b Not identical TRUE if $a is not equal to $b, or they are not of the same type.
      $a < $b Less than TRUE if $a is strictly less than $b.
      $a > $b Greater than TRUE if $a is strictly greater than $b.
      $a <= $b Less than or equal to TRUE if $a is less than or equal to $b.
      $a >= $b Greater than or equal to TRUE if $a is greater than or equal to $b.
      Examples:
      <?php
      var_dump(0 == "a"); 		// TRUE (0 == 0)
      var_dump("3" == "03");		// TRUE (3 == 3)
      var_dump(100 == "1e2");		// TRUE (100 == 100)
      var_dump(100 != "1e2");		// FALSE (100 != 100)
       
      var_dump(0 === 0); 		// TRUE (0 === 0)
      var_dump(0 === "a"); 		// FALSE (0 === 0 but types differ)
      var_dump(3 === "03"); 		// FALSE (3 === 3 but types differ)
      var_dump(3 !== "03"); 		// TRUE (3 === 3 but types differ)
       
      var_dump(3 > "03");		// FALSE (3 > 3)
      var_dump(3 >= "03");		// TRUE (3 >= 3)
      ?>

      A helpful tool is the Type Comparison Tables because it shows the different types of elements and how they are compared.

      Error Control Operator

      The error control operator is the at symbol ( @ ). When it is put in front of an expression, it ignores any error message that occurs from that expression. If track_errors = 1 in your php.ini file then error message that was generated will be saved in the variable $php_errormsg.

      Examples:
      <?php
      /* Intentional file error */
      $myFile = @file ('non_existent_file') or
          die ("Failed opening file: error was '$php_errormsg'");
      /*Prints: Failed opening file: error was 'file(non_existent_file) [function.file]: failed to open stream: No such file or directory' */
      ?>

      Incrementing/Decrementing Operators

      There are two types of incrementing/decrementing operators, post- and pre-. Post- does the operation after the expression, and pre- does the operation before the expression.

      Example Name Result
      ++$a Pre-increment Increments $a by one, then returns $a.
      $a++ Post-increment Returns $a, then increments $a by one.
      –$a Pre-decrement Decrements $a by one, then returns $a.
      $a– Post-decrement Returns $a, then decrements $a by one.
      Examples:
      <?php
      /* Post-increment */
      $a = 3;
      echo $a++;	// Prints 3 then increments 
      echo $a;	// Prints 4
       
      /* Pre-increment */
      $a = 3;
      echo ++$a;	// Increments then prints 4 
      echo $a;	// Prints 4
       
      /* Post-decrement */
      $a = 3;
      echo $a--;	// Prints 3 then decrements 
      echo $a;	// Prints 2
       
      /* Pre-decrement */
      $a = 3;
      echo --$a;	// Decrements then prints 2 
      echo $a;	// Prints 2
       
      /* Same can be done for characters */
      $b = 'M';
      echo ++$b;	// Prints N
      echo ++$b;	// Prints O
      ?>

      Logical Operators

      Example Name Result
      $a and $b And TRUE if both $a and $b are TRUE.
      $a or $b Or TRUE if either $a or $b is TRUE.
      $a xor $b Xor TRUE if either $a or $b is TRUE, but not both.
      ! $a Not TRUE if $a is not TRUE.
      $a && $b And TRUE if both $a and $b are TRUE.
      $a || $b Or TRUE if either $a or $b is TRUE.
      Examples:
      <?php
      $a = true and true	//TRUE
      $a = true and false	//FALSE
      $a = true or false	//TRUE
      $a = true xor true	//FALSE
      $a = !true		//FALSE
      $a = true && true	//TRUE
      $a = true || false	//TRUE
      ?>

      String Operators

      There are only two string operators. The first is the dot ( . ). It combines the string on its left to the strong on its right. The next string operator is the equals sign ( = ). It appends the argument on the right side to the left.

      Examples:
      <?php
      $a = 'Welcome ';
      $b = $a . 'Home!'; //  $b now contains 'Welcome Home!'
       
      $a = 'Welcome ';
      $a .= 'Home!';     // $a now contains 'Welcome Home!'
       
      echo 'nine'.'teen';	//prints the string "three'
      echo 'twe' . 'lve';	//prints the string 'twelve'
      echo 1 . 5;		//prints the string '15'
      echo 1.2;		//prints the number 1.2
      echo 1+2;		//prints the number 3
      ?>

      Array Operators

      Example Name Result
      $a + $b Union Union of $a and $b.
      $a == $b Equality TRUE if $a and $b have the same key/value pairs.
      $a === $b Identity TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
      $a != $b Inequality TRUE if $a is not equal to $b.
      $a <> $b Inequality TRUE if $a is not equal to $b.
      $a !== $b Non-identity TRUE if $a is not identical to $b.

      Most of the above operators, like equality and inequality, have already been explained above, so I am just going to concentrate on the new one: union. The union ( + ) operator joins the right hand array to the left hand. If keys exist in both, the right hand array values will be used. If keys exist in the left, but not the left, then the left hand array values will be used.

      Example:
      <?php
      $a = array("a" => "apple", "b" => "banana");
      $b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
       
      $c = $a + $b; // Union of $a and $b
      echo "Union of $a and $b: n";
      var_dump($c);
       
      $c = $b + $a; // Union of $b and $a
      echo "Union of $b and $a: n";
      var_dump($c);
      ?>

      The above results in:

      Union of $a and $b:
      array(3) {
        ["a"]=>
        string(5) "apple"
        ["b"]=>
        string(6) "banana"
        ["c"]=>
        string(6) "cherry"
      }
      Union of $b and $a:
      array(3) {
        ["a"]=>
        string(4) "pear"
        ["b"]=>
        string(10) "strawberry"
        ["c"]=>
        string(6) "cherry"
      }
      
      Note:

      All tables and most examples above were taken word for word from PHP.net’s PHP Operators – Manual. I do not claim to have written these, I just compiled them all together.

Leave a Reply

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

* Copy This Password *

* Type Or Paste Password Here *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 
© 2014 Not Just A Random Blog All rights reserved - Privacy Policy - Theme by ([][]) TwoBeers