24 Votes

PHP: Meaning of the Percent Sign as Operator

Question by Guest | Last update on 2024-01-14 | Created on 2014-06-05

I just sniffed a bit in some foreign PHP code and discovered an operator that I wasn't aware of before.

It is about the percentage symbol:

$v = $x % 10;

Obviously, it is used just like the operators +, -, * and /. But what can it mean?

ReplyPositiveNegative
3Best Answer3 Votes

The percent sign is the so-called modulus operator (MOD), which can be used not only in PHP but also in many other programming languages.

The modulus operator returns the remainder of a division operation.

Here are three examples:

  • 12 % 10 = 2 (10 fits one times in 12, 2 remains as rest)
  • 10 % 5 = 0 (5 fits exactly two times in 10, without any remainder)
  • 3 % 7 = 3 (7 does not fit any times in 3, so 3 remains)

This operator respectively the modulo operation can be used, for example, to create recurring rows or series of numbers. For instance, when increasing the variable $i within a loop, $i%2 alternately results in 0 or 1 at each iteration. $i%3 results in 0 in every third pass, and so on.
Last update on 2024-01-14 | Created on 2014-06-07

ReplyPositive Negative
Reply

Related Topics

PHP: Current Date and Time

Tutorial | 0 Comments

PHP: Upload of large Files

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.