PHP Tutorial - PHP Operators






PHP Assignment Operators

The assignment operators set the values of variables either by copying the value or copying a reference to a value. They are shown in the following table.

The following table lists the assignment operators used in PHP.

Operator Name Description
= Assignment$a = $b copies $b's value into $a
=& Reference $a =& $b set $a to reference $b

The following code shows how to use assignment operator to assign value to a variable.

<?PHP
$x = 4;
$x = $x + 4; // $x now equals 8

print $x;
?>

The code above generates the following result.





Assignment Operator Example

The following code shows how to use assignment operator.

<?php
  //Add 5 to Count
  $Count = 0;
  $Count = $Count + 5;

  //Add 5 to Count
  $Count = 0;
  $Count += 5;

  //prints 13
  print($a = $b = 13);
  print("<br>\n");

  //prints 7
  $Count = 2;
  print($Count += 5);
  print("<br>\n");
?>


The code above generates the following result.





PHP Arithmetic Operators

The arithmetic operators handle basic numerical operations, such as addition and multiplication.

The full list arithmetic operators in PHP is shown in the following table.

Operator MeaningOperation
+ Addition Returns the first value added to the second: $a + $b.
- Subtraction Returned the second value subtracted from the first: $a - $b.
* Multiplication Returns the first value multiplied by the second: $a * $b.
/ Division Returns the first value divided by the second: $a / $b.
% ModulusDivides the first value into the second, then returns the remainder: $a % $b. This only works on integers, and the result will be negative if $a is negative.
+= Shorthand addition Adds the second value to the first: $a += $b. Equivalent to $a = $a + $b.
-= Shorthand subtraction Subtracts the second value from the first: $a -= $b. Equivalent to $a = $a - $b.
*= Shorthand multiplication Multiplies the first value by the second: $a *= $b. Equivalent to $a = $a * $b.
/= Shorthand division Divides the first value into the second: $a /= $b. Equivalent to $a = $a / $b.

An exponentiation is done via the pow() function. Here are some examples.

<?PHP
      $a = 13; 
      $b = 4; 
      $c = 3.33; 
      $d = 3.99999999; 
      $e = -10; 
      $f = -4; 

      print $a + $b; 
      print "\n"; 
      print $a - $c; 
      print "\n"; 
      print $a * $d; 
      print "\n"; 
      print $a / $f; 
      print "\n"; 
      print $e % $b; 
?>

The code above generates the following result.

Arithmetic Operators Example

The following code shows how to use arithmetic operator.

<?php
  //prints 6
  print(2 + 2 * 2);
  print("<br>\n");

  //prints 2.5
  print(5 / 2);
  print("<br>\n");

  //prints 1
  print(5 % 2);
  print("<br>\n");

  //prints 35
  print(" 7 little Indians" * 5);
  print("<br>\n");
?>


The code above generates the following result.

PHP Incrementing and Decrementing Operators

We can use incrementing and decrementing operators to add one or subtract one from a numeric value.

There are two types of incrementing and decrementing operators.

Incrementing and decrementing operators do different things, depending on where you place them. The differences are summarized in the following table.

Statement NameMeaning
++$aPre-incrementIncrements $a by one, then returns $a
$a++Post-increment Returns $a, then increments $a by one
--$aPre-decrementDecrements $a by one, then returns $a
$a--Post-decrement Returns $a, then decrements $a by one

The incrementing and decrementing operators can be placed either before or after a variable, and the effect is different depending on where the operator is placed. Here's a code example:

<?PHP
      $foo = 5; 
      $bar = $foo++; 
      print "Foo is $foo\n"; 
      print "Bar is $bar\n"; 
      
      
      $counter=1;
      $counter--;
      echo $counter      
?>

The code above generates the following result.

Compare pre-increment to post-increment

The following code shows how to compare pre-increment to post-increment.

<?php
  $VisitorsToday = 1;

  //prints 1
  print($VisitorsToday++);

  //VisitorsToday is now 2
  print("<br>\n");

  //prints 3
  print(++$VisitorsToday);
  print("<br>\n");

  //prints 4.14
  $pi = 3.14;
  $pi++;
  print($pi);
  print("<br>\n");

  //prints PHQ
  $php = "PHP";
  $php++;
  print($php);
  print("<br>\n");

  //prints PHP
  $php = "PHP";
  $php--;
  print($php);
  print("<br>\n");
?>


The code above generates the following result.

PHP Comparison Operators

Comparison operators return either true or false, and thus are suitable for use in conditions.

Comparison operators in PHP has are listed in the following table.

Operator Name Description
==Equals True if $a is equal to $b
=== Identical True if $a is equal to $b and of the same type
!=Not equal True if $a is not equal to $b
<>Not equal True if $a is not equal to $b
!= = Not identical True if $a is not equal to $b or if they are not of the same type
< Less than True if $a is less than $b
> Greater than True if $a is greater than $b
<=Less than or equal True if $a is less than or equal to $b
>=Greater than or equal True if $a is greater than or equal to $b

The === (identical) says two variables are only identical if they hold the same value and if they are the same type, as demonstrated in this code example:

<?PHP
     print 12 == 12; 
     print 12.0 == 12; 
     print (0 + 12.0) == 12; 
     print 12  === 12; 
     print "12" == 12; 
     print "12" === 12; 
?>

The code above generates the following result.

Example Identical Operator

The === operator is useful when comparing against false with 0 and empty string.

For example, PHP considers an empty string (""), 0, and false to be equal when used with ==, but using === allows you to make the distinction. For example:

<?PHP
     if (0 === true) {                                                                               
        print(" this is true ");
     }                                                                                                
     if (0 === false) { 
        print("this is false ");
     } 
?>

PHP Logical Operators

We can use logical operators to combine boolean value and do the boolean logic arithmetic.

When resolving equations using logic, you can choose from one of six operators, listed in the following table.

Operator NameMeaning
ANDLogical AND True if both $a and $b are true
&& Logical AND True if both $a and $b are true
OR Logical OR True if either $a or $b is true
|| Logical OR True if either $a or $b is true
XORLogical XOR True if either $a or $b is true, but not both
! Logical NOT Inverts true to false and false to true: !$a

Boolean values to produce a result of either true or false :

Operator Example Result
&&(and) $x && $y true if both $x and $y evaluate to true ; false otherwise
and $x and $y true if both $x and $y evaluate to true ; false otherwise
|| (or) $x || $ytrue if either $x or $y evaluates to true ; false otherwise
or$x or $ytrue if either $x or $y evaluates to true ; false otherwise
xor $x xor $y true if $x or $y (but not both) evaluates to true ; false otherwise
! (not) !$xtrue if $x is false ; false if $x is true

Here are some simple examples of logical operators in action:

<?PHP
  $x = 2; 
  $y = 3; 
  echo ( ($x  >  1)  &&  ($x  <  5) ) .  "\n";
  echo ( ($x == 2) or ($y == 0) ) . "\n"; 
  echo ( ($x == 2) xor ($y == 3) ) . "\n";
  echo ( !($x == 5 ) ) . "\n";            
?>

The code above generates the following result.

The && and || are more commonly used than their AND and OR counterparts because they are executed before the assignment operator. For example:

$a = $b && $c;

The code above says "set $a to be true if both $b and $c are true.". But, if the && is replaced with AND, the assignment operator is executed first, which makes PHP read the expression like this:

($a = $b) AND $c;

This is sometimes the desired behavior. For example in the following statement.

do_some_func() OR die("do_some_func() returned false!");

In code above, do_some_func() will be called, and, if it returns false, die() will be called to terminate the script. The OR operator tells PHP to execute the second function only if the first function returns false.

PHP uses conditional statement short-circuiting. It reads "A or B must be true, and PHP finds A to be true, it will not evaluate B since the condition is satisfied." The same theory applies to and.

False value

In addition, PHP considers the following values to be false :

  • The literal value false
  • The integer zero (0)
  • The float zero ( 0.0 )
  • An empty string ( " " )
  • The string zero ( "0" )
  • An array with zero elements
  • The special type null (including any unset variables)
  • A SimpleXML object that is created from an empty XML tag

All other values are considered true in a Boolean context.

Short-circuit logical expressions Example

The following code shows how to use short-circuit logical expressions.


<?php
  $numerator = 5;
  $divisor = 0;
  if(($divisor == 0) OR (($num / $divisor) > 1))
  {
    print("The result is greater than 1");
  }
?>


The code above generates the following result.

PHP String Operators

There are only two string operators in PHP: concatenation and shorthand concatenation. Both are shown in the following table.

Operator Name Description
. Concatenation Returns the second value appended to the first: $a . $b
.= Shorthand concatenation Appends the second value to the first: $a .= $b

These operators are used to join strings together, like this:

<?PHP
      $first = "Hello, "; 
      $second = "world! from java2s.com"; 

      // join $first and $second; assign to $third 
      $third = $first . $second; 
      // $third is now "Hello, world!" 

      $first .= " officer!"; 
      // $first is now "Hello, officer!" 
?>

PHP Ternary Operator

The ternary operator is a shorthand for if statements.

PHP ternary operator has following syntax.

expression = ( expression1 ) ? expression2 : expression3;

The ternary operator takes three operands:

  • a condition (expression1),
  • a result(expression2) for true, and
  • a result(expression3) for false.

The preceding code reads as follows:

If expression1 evaluates to  true, 
  the overall expression equals  expression2 ;  
otherwise, 
  the overall expression equals  expression3 .  
<?PHP
$age = 10;
$agestr = ($age < 16) ? 'child' : 'adult'; 
print $agestr;
?>

The code above generates the following result.

That ternary statement can be expressed in a normal if statement like this:

<?PHP
      $age = 10;
      if ($age < 16) { 
             $agestr = 'child'; 
      } else { 
             $agestr = 'adult'; 
      } 
?>

PHP Bitwise Operators

Bitwise operators manipulate the binary digits of numbers.

The bitwise operators are listed in the following table.

Operator Name Description
& And Bits set in $a and $b are set.
| Or Bits set in $a or $b are set.
^ Xor Bits set in $a or $b, but not both, are set.
~ Not Bits set in $a are not set, and vice versa.
<< Shift leftShifts the bits of $a to the left by $b steps.
>> Shift right Shifts the bits of $a to the right by $b steps.

To give an example, the number 8 is represented in eight-bit binary as 00001000. In a shift left, <<, all the bits literally get shifted one place to the left, giving 00010000, which is equal to 16.

The & (bitwise and) operator returns a result with all the joint bits set.

Here's an example: given 52 & 28, we have the eight-bit binary numbers 00110100 (52) and 00011100 (28).

If PHP finds a 1 in both values, it puts a 1 into the result in the same place. Here is how that looks:

00110100 (52) 
00011100 (28)    &
-------------------
00010100 (20) 

Therefore, 52 & 28 gives 20.

Perhaps the most common bitwise operator is |, which compares bits in operand one against those in operand two, and returns a result with all the bits set in either of them. For example:

00110100 (52) 
11010001 (209)    |
------------------
11110101 (245) 

| (bitwise or) operator can combine many options together.

The following code shows how to use bitwise operators.

<?php
     $answers = 88;
     $question_four = 8;
   
     $answers = $answers & $question_four;
     print($answers . "<br />");
     $answers = $answers | $question_four;
     print($answers . "<br />");
     $answers = $answers ^ $question_four;
     print($answers . "<br />");
?>

The code above generates the following result.

PHP Execution Operator

Execution operator passes commands to the operating system for execution, then capture the results.

PHP uses backticks (`) as its execution operator.

The following code will run the command dir and output its results to the screen.

<?PHP
print `dir`; 
?>

The code above generates the following result.

PHP Operator Precedence

An operator with a higher precedence is executed before an operator with lower precedence. For example,

3 + 4 * 5

In the case of the example, * has a higher precedence than + , so PHP multiplies 4 by 5 first, then adds 3 to the result to get 23.

Precedence of Some PHP Operators (Highest First)

A list of the operators in order of precedence (highest first):

++  --  (increment/decrement)    
(int) (float) (string) (array) (object) (bool) (casting)    
! (not)    
* / % (arithmetic)    
+  -  . (arithmetic)    
<     < =  >     > =  <  >  (comparison)    
== != === !== (comparison)    
&&  (and)    
|| (or)    
= +=  - = *= /= .= %= (assignment)    
and     
xor    
or    

You can affect the order of execution of operators in an expression by using parentheses. So, for example, the following expression evaluates to 35:

( 3 + 4 ) * 5