Introduction to PHP operators

To perform ‘operations’ on variable or values, the programming languages provide operators. For example 10 + 5 = 15. Where 10 and 5 are called operands while ‘+’ and ‘=’ are operators.

PHP provides all type of operators that are required to perform operations and can be categorized into the following:

  1. Arithmetic Operators
  2. Comparison Operators
  3. Logical  Operators
  4. Assignment Operators
  5. Ternary Operators also knows as conditional operators

PHP Assignment Operator

The “=” sign is an assignment operator in PHP. This is used to assign the value to variables.

Examples:

$Int_var = 10;

$Str_var  = “String Variable Assignment”

$a = $b; //Assigning one variable value to other

PHP Arithmetic operators

To perform mathematical operations, PHP provides following arithmetic operators.

OperatorNameExample
+Addition$a = 10 + 10;
Subtract$a = 20 – 10;
*Multiply$a = 5 * 5;
/Divide$a = 50/5;
%Modulus$a % $b

Using Assignment Operator with Arithmetic operators

AssignmentWill be taken asName
a += ba = a + bAddition
a -= ba = a – bSubtraction
a *= ba = a * bMultiplication
a /= ba = a / bDivision
a %= ba = a % bModulus

Increment/Decrement Operators in PHP

OperatorNameDescription
++$aPre-incrementIncrements $a by one, then returns $a
$a++Post-incrementReturns $a, then increments $a by one
–$aPre-decrementDecrements $a by one, then returns $a
$a–Post-decrementReturns $a, then decrements $a by one

The Comparison Operators

The comparison operators are used to compare two values, numbers or strings. It results in true or false. For example, if $y=10 and $z=20 then following will result as follows

OperatorDescriptionExample and result
==Checks if two operands are equal or not.(y == z) is not true.
!=Checks if “not equal to”(y != z) is true.
>Greater than(y > z) is not true.
<Checks if less than(y < z) is true.
>=Greater than or equal to(y >= z) is not true.
<=Less than or equal to(y <= z) is true.

Logical Operators

OperatorNameExampleResult
andAnd$x and $yTrue if both $x and $y are true
orOr$x or $yTrue if either $x or $y is true
xorXor$x xor $yTrue if either $x or $y is true, but not both
&&And$x && $yTrue if both $x and $y are true
||Or$x || $yTrue if either $x or $y is true
!Not!$xTrue if $x is not true

PHP String Operators

As we have used in our chapters, the . (period) and .= operators are used as string operators.

The .(period) is used for Concatenation purpose. See example below

Experience this example online

Output

This is Concatenation example!

Usage of Concatenation assignment (.=) example

Experience this example online

Output

This is Concatenation example!