PHP Basics

PHP Arithmetic Operators

To perform arithmetic operations PHP has operators that performs the task.

Operators

Addition Operator

As the name says, arithmetic operator performs arithmetic operation. The symbol of addition operator is +

Example

<?php

$num1=10;

$num2=20;

echo $num1+$num2;

?>

Output:30

Subtraction Operator

Subtraction Operator performs subtraction operation. The symbol of subtraction operator is –

Example

<?php

$num1=20;

$num2=10;

echo $num1-$num2;

?>

Output: 10

Multiplication Operator

Multiplication operator performs multiplication operation. The symbol of multiplication operator is *

Example

<?php

$num1=5;

$num2=10;

echo $num1*$num2;

?>

Output: 50

Division Operator

Division operator performs division operations. The symbol of division operator is /

Example

<?php

$num1=100;

$num2=50;

echo $num1/$num2;

?>

Output:2

Modulus Operator

Modulus Operator performs modulus operation. The symbol of modulus operator is %

What is modulus operation?

Modulus operation gives us the remainder of division of two numbers.

Example

<?php

$num1=25;

$num2=10;

echo $num1%$num2;

?>

Looking at the above code we can say the remainder will be 5.

So using Modulus operator, we can get the remainder of division of two numbers.

Increment Operator

To understand what is an Increment Operator, lets consider a simple situation. A requirement came to increment a value by 1 then how could we achieve this?

<?php

$num1=10;

$num1=$num1+1;

echo $num1;

?>

Output: 11

Note: In the second line of the above code, we have added 1 to the value of the variable name $num1 and then we assigned back to itself that is $num1. ($num1=$num1+1);

Now, the below code is also going to provide us the same result.

<?php

$num1=10;

$num1++;

echo $num1;

?>

Output:11

Note: Look at the second line in the above example. There is a double plus symbol beside to the variable name. This double plus sign is known as increment operator.

$num1++ is equivalent to $num1=$num1+1

What does an increment operator do?

An increment operator increments the value of the variable by 1.

Decrement Operator

Decrement operator is similar to increment operator except it decrements the value of the variable by 1. And the symbol for decrement operator is double minus sign —

Example

Decrement the value of variable by 1

<?php

$num1=10;

$num1–;

echo $num1;

?>

Output: 9