Image

PHP - Operator - Operators

Operators

When comparing or processing variables and other values you use operators. Without them, PHP would be more of a word jumble instead of a language. In some unique cases, operators slightly alter the relationship between two variables or their function within PHP. Without further adieu, here they are.


Basic Operators
Add ( + )$a = 1; $a = $a + 5; // $a is equal to 6
Subtract ( - )$s = 10; $s = $s - 5; // $s is equal to 5
Multiply ( * )$m = 2; $m = $m * 10; // $m is equal to 20
Divide ( / )$d = 20; $d = $d / 5; // $d is equal to 4
Modulus ( % )Provides the remainder after division: $u = 5; $u = $u % 2; // $u is equal to 1

Assignment Operators
Add ( += )$a = 1; $a += 5; // $a is equal to 6
Subtract ( -= )$a = 1; $a += 5; // $a is equal to 6
Multiply ( *= )$m = 2; $m *= 10; // $m is equal to 20
Divide ( /= )$d = 20; $d /= 5; // $d is equal to 4
Modulus ( %= )Provides the remainder after division: $u = 5; $u %= 2; // $u is equal to 1
Concatenate ( .= )Join onto the end of a string: $c = 5; $c .= 2; // $c is now a string, '52'

Comparison Operators
Greater Than ( > )2 > 1
Less Than ( < )1 < 2
Greater Than or Equal To ( >= )2 >= 2 3 >= 2
Less Than or Equal To ( <= )2 <= 2 2 <= 3

Increment decrement operator

Increment ( $integer++; )

Decrement ( $integer--; )

Example:
$a = 1;
$a = $a + 1; // $a is now equal to 2
$a++; // $a is now equal to 3
$a--; // $a is now equal to 2 again, same as $a = $a – 1;

Ternary operator

The Ternary Operator is a short-hand form for evaluating what to do when an expression is evaluated as either TRUE or FALSE. The conditional returns either the TRUE or FALSE output. Basic format is as follows:

(expr) ?ValueIfTrue :ValueIfFalse ;
Examples:
$boolean = TRUE;
$result = ($boolean) ? 'Is True' : 'Is False';
echo $result;
Is True
// $result is not yet set
$result = (isset($result)) ? $result+1 : 10;
echo " \$result = $result.";
$result = (isset($result)) ? $result+1 : 10;
echo " \$result = $result.";
$result = 10. $result = 11.