PHP 2 same calculation but different outcome, why? [duplicate] - php

This question already has answers here:
php operator precedence
(5 answers)
Closed 7 months ago.
My apologies for this question but I am brand new with PHP.
So I tried out 2 same calculations in PHP but I get different outcome.
Here are the samples.
<?php
$var = 4;
$var = $var * 23;
$var = $var - 46;
$var = $var + 86;
$var = $var / 2;
$var++;
print $var;
?>
Outcome is 67
<?php
$var = 4;
$var = ($var * 23) - 46 + 86 / 2;
$var++;
print $var;
?>
outcome is 90
So basically they were correct until when its on the line where it says / 2.
On that line it changes the outcome. Anyone knows why?

Both expressions are not same although they look same to the naked eye.
$var = ($var * 23) - 46 + 86 / 2;
is the same as
$var = ($var * 23) - 46 + (86 / 2);
because division takes precedence over addition in computers. If you wish to overrule this, use braces (), like $var = ($var * 23 - 46 + 86) / 2;.
There are several other examples you may want to learn like below:
Snippet:
<?php
echo 86 + 4 / 2, "\n"; // gives 88
echo 86 * 4 / 2, "\n"; // same as (86 * 4) / 2, gives 172
echo 86 % 3 / 4, "\n"; // same as (86 % 3) / 4, gives 0.5
echo 86 % 3 * 4 / 5,"\n"; // same as ((86 % 3) * 4) / 5, gives 1.6
echo 86 * 3 % 4 / 5; // same as ((86 * 3) % 4) / 5, gives 0.4
Online Demo
Between %, * and /, it is all about order from left to right. Whoever comes first, will have their precedence over the other.

you have to change
$var = ($var * 23) - 46 + 86 / 2;
to
$var = (($var * 23) - 46 + 86) / 2;
In the first example (which you did), 86 is first divided by 2. In the next, the whole expression is divided by 2.
I suggest you review this manual.
https://www.php.net/manual/en/language.operators.precedence.php

What makes you think the both calculations are equal? A division has higher precedence than an addition, + 86 / 2 is not evaluated from left to right

Related

Strange Modulus Operator Result - PHP

I am working on a PHP application and mathematical operation was resulting wrong answer which was displaying wrong results. So, I started digging down and after few hours effort I was able to detect the issue.
Here is the problematic Expression:
echo -1 % 26;
The answer should be 25 but it gives -1. I don't know, is there anything wrong with my expression?
PHP Output:
Calculator:
Can anyone please identify, where is the problem?
This is the expected behaviour. From the PHP manual
The result of the modulo operator % has the same sign as the dividend — that is, the result of $a % $b will have the same sign as $a
If the sign of the dividend (the part to the left of the %) changes, the result will also change. You can find the positive equivalent of a negative remainder by adding the divisor. -1 is equivalent to 25 modulo 26 since -1 + 26 = 25.
Hence you can do the following to get the positive result:
function modulo($dividend, $divisor) {
$result = $dividend % $divisor;
return $result < 0 ? $result + $divisor : $result;
}
$calculation = modulo(-1, 26); // 25
$calculation2 = modulo(51, 26); // 25
How about ?
$ cat test.php
<?php
function truemod($num, $mod) {
return ($mod + ($num % $mod)) % $mod;
}
echo truemod(-1, 26).PHP_EOL;
?>
Output
$ php test.php
25

Why this php code output one

I have this php code with me and i am not able to figure it out could anyone help on this.
$x = 3 - 5 % 3;
echo $x;
gives 1 in out put.
Thanks
5 % 3 = 2.
3 - 2 = 1.
There's a specific operator precedence, that causes modulo to be evaluated before minus.
It' s simple math!
% / * operators are first calculated and then
+ -
5 % 3 = 2
3 - 2 = 1
If you want to "prevent" this simply add some brackets:
$x = (3 - 5) % 3;
Of course the answer is correct. PHP parses the code like this 3 - (5 % 3)
5 % 3 is 2 and 3 - 2 gives you 1
5 % 3 is the remainder of 5 /3
It's the order of operations. Without parenthesis around the subtraction, the modulo is being evaluated first. Try this:
$x = (3 - 5) % 3;
echo $x;
% has higher presedence then -. Check out operator precedence
BODMAS - Brackets Order[^] Division Multiplication Addition Substracion .
For,
3 - 5 % 3
first,
5 % 3 gives remainder as 1
second,
3 - 1,
this gives 2.

Total a natural number with real number by php?

How can increase a number according to percent with PHP?
For example: 100 + 20% = 120 or 1367 + 33% = 1818.11
If output was this: 1818.11 i want only this: 1818 or this 12.32 = 12 or 546.98 = 546
How is it?
I'm not sure if you're looking for something deeper, but the answer seems fairly straightforward...
$increasedValue = floor( $value * ( 1 + ( $percentageIncrease / 100 ) ) );
If you wrapped that in a function, say increaseByPercentage( $value, $percentageIncrease ), you would get...
increaseByPercentage( 100, 20 ); //returns 120
increaseByPercentage( 1367, 33 ); //returns 1818
Edit
Based on your comment, I'm not sure what else you are looking for. PHP has 6 arithmetic operators:
Negation (-$a)
-5 = -5
Addition ($a + $b)
5 + 3 = 8
Subtraction ($a - $b)
5 - 3 = 2
Multiplication ($a * $b)
5 * 3 = 15
Division ($a / $b)
5 / 3 = 1.667
Modulus ($a % $b)
5 % 3 = 2
If you write a line of code that says $a = 100 + 20%; it will not parse.
function addPercent($number, $percent)
{
return (int)($number+$number*($percent/100));
}
echo addPercent(1367, 33); // 1818
Just cast the result into an Integer.
Edit: My method isn't quite right. It looks like Farray has outlined a better one as well.
Is this what you want?
round( 156 + 156 * ( 20/100 ) )
Normally without round() this would = 187.2. With round(), it's equal to 187.

bad value in calculation output

The following code outputs "3". I was expecting "1".
echo $resultado."\n"; // show 2
$valor = $resultado * ($resultado - 1 / 2);
echo $valor."\n"; // show 3, and should be 1
Why does this happen?
Because the division 1 / 2 takes precedence in the order of operations. So you have really have this expression:
$resultado * ($resaltudo - (1 / 2))
You should add parenthesis to be:
$resultado * (($resaltudo - 1) / 2)
to get the answer you want.
No, you're wrong. The / has priority on - and so your line is like:
$valor = $resultado * ($resultado - (1 / 2));
and that is:
$valor = 2 * (2 - 0.5); // and so $valor = 3
That's because the division operator (/) has a higher precedence than the subtraction operator (-).
Your expression becomes, in order:
1 / 2 = 0.5 // Executed first since it's the highest precedence operation inside ()
$resultado - 0.5 = 1.5 // Still in the ()
$resultado * 1.5 = 3 // Final result
To correct your expression, insert parethesis around the subtraction, like this:
$resultado * (($resultado - 1) / 2);
The / takes precedence over + or -
To get 1 as a result you need to use
$resultado * (($resultado - 1) / 2)
Replacing $resultado in the expression, you get:
$valor = 2 * (2 - 1 / 2);
2 - 1 / 2 = 1.5
2 * 1.5 = 3
My suggestion is review basic math ;)
Change it to:
echo $resultado."\n";
$valor = $resultado * (($resultado - 1) / 2);
echo $valor."\n";
You were effectively doing 2 * (2 - (1 / 2) = 2 * 1.5 = 3
2*(2-1/2)
The dividing operator has higher order operator precedence than the minus sign, so the computer will calculate it like this:
2*(2-(1/2)) = 2 * 1.5 = 3
Use parentheses liberally.

What does the percent sign mean in PHP?

What exactly does this mean?
$number = ( 3 - 2 + 7 ) % 7;
It's the modulus operator, as mentioned, which returns the remainder of a division operation.
Examples: 3%5 returns 3, as 3 divided by 5 is 0 with a remainder of 3.
5 % 10 returns 5, for the same reason, 10 goes into 5 zero times with a remainder of 5.
10 % 5 returns 0, as 10 divided by 5 goes exactly 2 times with no remainder.
In the example you posted, (3 - 2 + 7) works out to 8, giving you 8 % 7, so $number will be 1, which is the remainder of 8/7.
It is the modulus operator:
$a % $b = Remainder of $a
divided by $b.
It is often used to get "one element every N elements". For instance, to only get one element each three elements:
for ($i=0 ; $i<10 ; $i++) {
if ($i % 3 === 0) {
echo $i . '<br />';
}
}
Which gets this output:
0
3
6
9
(Yeah, OK, $i+=3 would have done the trick; but this was just a demo.)
It is the modulus operator. In the statement $a % $b the result is the remainder when $a is divided by $b
Using this operator one can easily calculate odd or even days in month for example, if needed for schedule or something:
<?php echo (date(j) % 2 == 0) ? 'Today is even date' : 'Today is odd date'; ?>
% means modulus.
Modulus is the fancy name for "remainder after divide" in mathematics.
(numerator) mod (denominator) = (remainder)
In PHP
<?php
$n = 13;
$d = 7
$r = "$n % $d";
echo "$r is ($n mod $d).";
?>
In this case, this script will echo
6 is (13 mod 7).
Where $r is for the remainder (answer), $n for the numerator and $d for the denominator. The modulus operator is commonly used in public-key cryptography due to its special characteristic as a one-way function.
Since so many people say "modulus finds the remainder of the divisor", let's start by defining exactly what a remainder is.
In mathematics, the remainder is the amount "left over" after
performing some computation. In arithmetic, the remainder is the
integer "left over" after dividing one integer by another to produce
an integer quotient (integer division).
See: http://en.wikipedia.org/wiki/Remainder
So % (integer modulus) is a simple way of asking, "How much of the divisor is left over after dividing?"
To use the OP's computation of (3 - 2 + 7) = 8 % 7 = 1:
It can be broken down into:
(3 - 2 + 7) = 8
8 / 7 = 1.143 #Rounded up
.143 * 7 = 1.001 #Which results in an integer of 1
7 can go into 8 1 time with .14 of 7 leftover
That's all there is to it. I hope this helps to simplify how exactly modulus works.
Additional examples using different divisors with 21.
Breakdown of 21 % 3 = 0:
21 / 3 = 7.0
3 * 0 = 0
(3 can go into 21 7 times with 0 of 3 leftover)
Breakdown of 21 % 6 = 3:
21 / 6 = 3.5
.5 * 6 = 3
(6 can go into 21 3 times with .5 of 6 leftover)
Breakdown of 21 % 8 = 5:
21 / 8 = 2.625
.625 * 8 = 5
(8 can go into 21 2 times with .625 of 8 leftover)

Categories