How to add number to the PHP variable ?
If you don't know PHP basics or you are the beginner of PHP basic course. This article is for you to know about the variable. Basically, a variable is like a container. Always write a dollar sign ($) before the variable. After that, you have to give an equal to sign and then put the number for that variable. Don't forget to put a semicolon at the end of the variable declaration.
$Variable = 10;
What should we do, for instance, when we want to add 50 to a variable? To do this, we simply need to add the number to the variable and assign that result back to the variable. We can do other calculations like subtraction in the same way.
$Vr = 1;
$Vr = $Vr + 50 ;
[ Note : Add 50 to the $Vr variable and assign the value to the variable itself.]
echo $Variable;
// Output 51
Now you have to learn about Shorthand version of addition, subtraction, division, multiplication of the variable. Which is very useful for advanced PHP coder.
ShortHand Syntex : $variable += number;
$P = $P + 50; [Shorthand version is $P += 50;]
$P = $P - 50; [Shorthand version is $P -= 50;]
$P = $P * 50; [Shorthand version is $P *= 50;]
$P = $P / 50; [Shorthand version is $P /= 50;]
$P = $P % 50; [Shorthand version is $P %= 50;]
When you're adding or subtracting 1, you can shorten it further with the increment operator ++ and the decrement operator --. When you put an increment operator in front of a variable, the calculation gets done before echo. However, if an increment operator is put after a variable, the calculation is performed after echo.
Example :
$P += 1; or $P++;
$P -= 1; or $P--;
For an example,
$Q = 2 ;
$W = 2 ;
echo ++$Q; // Output : 3 [ Add 1 before running echo]
echo $W++; // Output : 2 [ Add 1 after running echo]

No comments