PHP modulus operator example

PHP FAQ: Can you share an example of how to use the PHP modulus operator?

Sure, here are two examples of how to use the PHP modulus operator. In this first example, because the remainder (the modulus, or technically, the modulo) of 100 divided by 5 is zero, the string "a was 0" will be printed:

<?php
  $a = 100 % 5;

  // php modulus operator
  if ($a == 0)
    echo "a was 0\n";
  else
    echo "a was $a\n";
?>

In this more real-world example, the function do_something will be called whenever the variable $count divided by 1,000 is zero:

<?php

  // some code up here ...

  // php modulus operator
  if ($count % 1000 == 0)
  {
    do_something();
  }

  // more code down here ...

?>

I do something like this when I generate the sitemap files for this website. I try to keep each sitemap file at no more than 1,000 URLs, so I use code like this to stop writing one file, and then start writing the next file.