Operators in Php

Assignment Operators

Assignment operators are used to assign a value or set a variable to another variable's value. Such an assignment  is done with the "=", or equal character.
Example:
  • $var = 11;
  • $another_var = $var;
Now both $my_var and $another_var contain the value 11. Assignments can also be used with arithmetic operators.

Arithmetic Operators

OperatorMeaningExample
+ Addition 12 + 14
- Subtraction 16 - 12
* Multiplication 15 * 13
/ Division 15 / 3
% Modulus 43 % 10

Example:

$addition = 12 + 14; 
$subtraction = 16 - 12; 
$multiplication = 15 * 13; 
$division = 15 / 3; 
$modulus = 15 % 12; 
echo "addition: 12 + 14 = ".$addition."<br />"; 
echo "subtraction: 16 - 12 = ".$subtraction."<br />"; 
echo "multiplication:  15 * 13 = ".$multiplication."<br />"; 
echo "division: 15 / 3 = ".$division."<br />"; 
echo "modulus: 15 % 12 = " . $modulus 
 . ". Modulus is the remainder after the division operation.

Result:

addition: 12 + 14 = 26
subtraction: 16 - 12 = 4
multiplication: 15 * 13 = 195
division: 15 / 3 = 5
modulus: 15 % 12 = 1. Modulus is the remainder after the division operation.

Comparison Operators

Comparisons are used to check the relationship between variables and/or values.Here are the most important comparison operators of PHP.

OperatorMeaning Example Result
== Equal To $x == $y false
!= Not Equal To $x != $y true
< Less Than $x < $y true
> Greater Than $x > $y false
<= Less Than or Equal To $x <= $y true
>= Greater Than or Equal To $x >= $y false

String Operators

"." is used for concatation operator for strings in php.
Example :

$string1 = "Hiren";
$string2 = "Prajapati";
$result= $string1 ." ". $string2;
echo $result. "!";

Result:

Hiren Prajapati!

Array Operators

Operator Meaning Description
x + y Union Union of x and y
x == y Equality True if x and y have the same key/value pairs
x === y Identity True if x and y have the same key/value pairs in the same order and of the same types
x != y Inequality True if x is not equal to y
x <> y Inequality True if x is not equal to y
x !== y Non-identity True if x is not identical to y

Logical Operators

Example Meaning/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.

Pre/Post-Increment & Decrement

    
 To add one to a variable or "increment" use the "++" operator: 
      $xyz++; Which is equivalent to $xyz += 1; or $x = $xyz + 1;
 To subtract 1 from a variable, or "decrement" use the "--" operator:
      $xyz--;  Which is equivalent to $xyz -= 1; or $xyz = $xyz - 1;
In addition to this "shorterhand" technique, you can specify whether you want to increment before the line of code is being executed or after the line has executed.

No comments: