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
  • 25,449
  • 7
  • 45
  • 62
GasKa
  • 663
  • 5
  • 25
  • 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
  • 25,449
  • 7
  • 45
  • 62
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
  • 32,350
  • 30
  • 109
  • 146