PHP operators | Using assignment, ternary, arithmetic operators

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 following:

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

A Short Video of operators Tutorial

 

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.

Operator Name Example
+ 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

Assignment Will be taken as Name
a += b a = a + b Addition
a -= b a = a – b Subtraction
a *= b a = a * b Multiplication
a /= b a = a / b Division
a %= b a = a % b Modulus

Increment/Decrement Operators in PHP

Operator Name Description
++$a Pre-increment Increments $a by one, then returns $a
$a++ Post-increment Returns $a, then increments $a by one
–$a Pre-decrement Decrements $a by one, then returns $a
$a– Post-decrement Returns $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

Operator Description Example 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

Operator Name Example Result
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True 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!