0

I just started to learn PHP deeper for Zend PHP certification and I found this code, which actually works. Can someone explain me the logic behind this?

<?php
$num = 20% - 8;
echo $num; // 4
Qirel
  • 23,315
  • 7
  • 41
  • 57
GasKa
  • 623
  • 5
  • 22
  • 3
    % is not per cent, but modulus, cf. https://en.m.wikipedia.org/wiki/Modular_arithmetic – MrTux Jul 10 '19 at 06:30

2 Answers2

2

What you're seeing is the modulus operator, which in essence asks "What is the remainder of 20 divided by -8".

So you might ask, why isn't it negative 4? From the 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.

See the PHP: Arithmetic Operators for more documentation.

Qirel
  • 23,315
  • 7
  • 41
  • 57
1

% is not per cent, but modulus, cf. https://en.m.wikipedia.org/wiki/Modular_arithmetic

20 = 2 * 8 + 4, therefore, 20 % 8 = 4

MrTux
  • 30,335
  • 25
  • 102
  • 137