jump to navigation

The Modulus Operator in PHP November 13, 2012

Posted by Tournas Dimitrios in PHP.
trackback

In mathematics the modulus operation is used to find the remainder of division between two numbers . Given two positive numbers , the dividend (x) and the divisor (y) , a modulo is the remainder of the Euclidean division of x by y (x/y) . For instance , the expression “5 modulus 3” would evaluate to 2 because 5 divided by 3 leaves a quotient of 1 and a remainder of 2 . Another example ,  “9 modulus 3” would evaluate to 0 because the division of 9 by 3 has a quotient of 3 and leaves a remainder of 0 ( there is nothing to subtract from 9 after multiplying 3 times 3) .We’ve been doing this since our fourth grade in elementary school , when we first learned long divisions and remainders . That’s essentially modulus — simply we didn’t knew what we did then 🙂 . For some unexplained reason , modulus is sometimes a hard concept to grasp , even by adults  .

Modulus is the “fifth” arithmetic operator that we have in our PHP toolbox . It’s a lesser known operator because it isn’t highly useful at first glance . However , it can be very useful in some cases . the following six code-snippets present posible practical implementations :

  • Evaluating a number  (is it odd or even)
    <?php
    $numbers = array(66 , 57 , 89 , 33 , 22 ) ;
    foreach($numbers as $num)
    {
    $m = ($num % 2);
    if ($m==0)
    {
    echo $num , "  is even " , "<br>";
    }else {
    echo $num , "  is odd " , "<br>";
    }
    }
    // Further simplified code
    foreach($numbers as $num)
    {
    if($num % 2) {
    echo "$num is odd<br />";
    } else {
    echo "$num is even<br />";
    	}
    }
    
  • Evaluating the thousands of a number
    <?php
    for($i = 1; $i < 10025; $i++) {
    if ($i % 1000 == 0)
      {
        echo "Another thousand is : " . $i .'
    '  ;
      }
    }
    
    
  • Challenge math , for instance : print out all factors of 9 between 20 and 250
    <?php
     $i = 25;
     while ( $i <= 250 )
     	{
    $m = ($i % 9);
    if ($m==0)
    {
    echo $i."
    ";
    }
    $i++;
    }
    
    
  • to have different visual representation (background color) for alternating rows in a HTML-table .
    <html>
    <head>
    <title>zebra table</title>
      <style type="text/css">
        #mytable tbody tr.even td{
          background-color: #d3ecf5;
        }
        #mytable tbody tr.odd td{
          background-color: #ff0;
        }
      </style>
    <body>
    <table id='mytable'>
      <tbody>
          <?php
    $myData = array( 'one' ,'two' , 'three' , 'four' , 'five') ; 
    $row = 0 ; 
    	  foreach($myData as $data): ?>
     <tr class="<?php echo fmod($row , 2) ? 'even' : 'odd' ?>">
            <td>
              <?php echo $data;  $row++?>
            </td>
          </tr>
        <?php 	endforeach; ?>
      </tbody>
    </table>
    </body>
    </html>
    
  • figuring out if a year is leap
    <?php
    // By using the date()  function 
    for($i = 2012 ; $i < 2025 ; $i++) {
     echo $i, ': ', (date('L', strtotime("$i-01-01")) ? 'Yes' : 'No'), '<br>' ;
    }
    
    
    // By using the modulus operator
    for($i = 2012 ; $i < 2025 ; $i++) 
    {
    if(($i%4) == 0)
    {
    $val = "Leap Year <br>" ;
    } else {
    $val = "Not Leap Year<br>" ;
    }
    echo $i , ' ---> '. $val  ;
    }
    
    
  • Another use is in credit card validation . Ever wonder how websites can figure out if your credit card is valid ? They use a mod 10 algorithm , which is something that most credit cards conform to .
    <?php
    //http://www.codeguru.com/cpp/i-n/internet/security/article.php/c15307/PHP-Tip-Validating-a-Credit-Card.htm
    function validate_cc_number($cc_number) {
       /* Validate; return value is card type if valid. */
       $false = false;
       $card_type = "";
       $card_regexes = array(
          "/^4\d{12}(\d\d\d){0,1}$/" => "visa",
          "/^5[12345]\d{14}$/"       => "mastercard",
          "/^3[47]\d{13}$/"          => "amex",
          "/^6011\d{12}$/"           => "discover",
          "/^30[012345]\d{11}$/"     => "diners",
          "/^3[68]\d{12}$/"          => "diners",
       );
    
       foreach ($card_regexes as $regex => $type) {
           if (preg_match($regex, $cc_number)) {
               $card_type = $type;
               break;
           }
       }
    
       if (!$card_type) {
           return $false;
       }
    
       /*  mod 10 checksum algorithm  */
       $revcode = strrev($cc_number);
       $checksum = 0;
    
       for ($i = 0; $i < strlen($revcode); $i++) {
           $current_num = intval($revcode[$i]);
           if($i & 1) {  /* Odd  position */
              $current_num *= 2;
           }
           /* Split digits and add. */
               $checksum += $current_num % 10; if
           ($current_num >  9) {
               $checksum += 1;
           }
       }
    
       if ($checksum % 10 == 0) {
           return $card_type ;
       } else {
           return $false;
       }
    }
    
    

Many programming languages (including PHP) use the % symbol to represent a modulo operation , for instance ,  a 6 modulo 4 is written  as 6%4 .

Comments»

1. lina - November 13, 2012

thank you very much for sharing all this great information with us! it’s definitely appreciated. well worth the time in reading!

2. mestreseo - December 6, 2012

this is a great inspiring article. i am pretty much pleased with your good work. you put really very helpful information. keep it up. keep blogging. looking to reading your next post.

3. Antony - December 6, 2012

your website is so organized, and your posts are always common sense, congratulations for making the difference.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s