2

Just came across this problem, would you mind explaining how this end up having an answer of 4? So basic yet I have no idea how it happened.

echo $a = 20%-8; //4

Answer:

echo (5 % 3)."\n";           // prints 2
echo (5 % -3)."\n";          // prints 2
echo (-5 % 3)."\n";          // prints -2
echo (-5 % -3)."\n";         // prints -2
1
  • 1
    The % is modulo operator, a remainder of integer division. When you divide 20 by -8, the integer remainder is 4. Commented Nov 3, 2014 at 9:05

4 Answers 4

2

% operator will leave the reminder of the operation. That is $x % $y will result in the remainder of $x divided by $y.

Here, when 20 divided by -8, it will leave reminder 4 which is the answer.

Sign up to request clarification or add additional context in comments.

Comments

1

You're trying to get a modulo of negative number. There's no difference between this and: 20%8

See: https://math.stackexchange.com/questions/519845/modulo-of-a-negative-number

Comments

1

@bwaaaaaa,Modulus operator will give the reminder of the operation.

Suppose $x % $y, that means that Remainder of $x divided by $y.

So for your example when 20 divided by -8 will gives you reminder 4 so its output is 4.

For More info. regarding modulas operator please visit this

2 Comments

thanks! i was confused with the -8. finally understood what modulus operation is.
@bwaaaaaa,Glad i could help ! If my answer really helpful to you,can you please accept my answer ?
0

The remainder operator returns the remainder left over when one operand is divided by a second operand. remember that the modulo operator result would always takes the sign of the dividend, not the divisor. It uses a built-in modulo function to produce the result, which is the integer remainder of dividing var1 by var2.

So here in your code the var1 is 20 which is positive integer and var2 is -8 which is negative integer. 20 is dividend and -8 is divisor.

so As we know the module operator result would take the sign of the dividend, not the divisor. That's why reminder answer will be just 4. Hope so now it is clear. thank you

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.