PHP: Operators
PHP assignment operator as most of the languages is equal to sign (=). Therefore, we can assign any variable any value using equal sign.
$my_variable = "my world";
$this_variable = 5;
PHP arithmetic operators include:
addition + (example: 2 + 4) , subtraction - (example: 4 -2) ,multiplication *( example: 4 * 3), division / (example: 4/2), modulus % (example 10 % 3).
Modulus gives the remainder after the division is performed. Therefore, 45 %2 would give 1, since, 1 is the remainder left when 45 is divided by 2.
PHP comparison or conditional operators used when if-else (or similar conditional operations) operations are done for checking conditions between variables and values include:
== (equal to), != (not equal to), < (less than), >(greater than), >= (greater than equal to), <= (less than equal to).
We can combine assignment operations for shorthand purposes as follows:
|
<?php $x = 0; $y = 0; $x = $x + 2; // same as $y += 2; // $y = 2 $y -= 1; // $y = 1 $y *= 2; // $y = 2 $y /= 2 ; //$y =1 $y %= 1; //$y = 0 $x = 4; $x++; // is same as $x = $x + 1 or $x += 1; would give 5. $x-- ; // same as $x = $x -1 or $x-= 1; would give 4. ?> |
Also, $x++ known as post-increment and ++x as pre-increment. Similarly, $x-- and --$x are known as post-decrement and pre-decrement.
The difference between post and pre operators is illustrated below:
|
<?php $x = 5; echo $x++; // would give 5. echo $x; // would give 6. $x = 5; echo ++$x; // would give 6. echo $x; // would give 6 ?> |
$x++ would execute after the line has executed and ++x would execute first and then the line in which it is present is executed. Thus, in post-increment ($x++) line is echoed wihout increasing the number and later it was found that the number has increased. In pre-incrment (++$x), the increased number value is reflected in the the line itself where it was applied.
PHP String operators include concatenation that is done by period(.) sign as follows:
|
<?php $string = "Hello "; $name = "Bob " ; $greet =$string.$name." nice meeting you! "; $greet .= "My pleasure!"; echo $greet; ?> |
This would give following output:
Note, that string were concatenated using period (.) and later shorthand notation of .= was used that is equivalent to $x = $x .$y.