Community Documentation

Generate A Random Number, Apply a Check Digit

Last updated December 20, 2010. Created by jayhariani on December 20, 2010.
Log in to edit this page.

I needed to create a field that would contain a unique serial number for certain node types. Using Computed Field, this was pretty easy. But, the twist was that the serial number would need to contain a check digit. To avoid ever re-generating the serial number and overwriting an existing value, I check to see if the field is not-empty.

if (!empty($node_field[0]['value'])) {  // The PIN has already been generated, do nothing

  return $node_field[0]['value'];

}

else {  // Time to create a PIN. Generate a random number,  calculate a check digit via modulus-9, and append the check digit to the generated number

$pin = rand(1000000,2000000);
$numArray = explode(" ", $pin);
$arraySum = array_sum($numArray); 
$remainder = $arraySum % 9;
$difference = 9 - $remainder; 
$node_field[0]['value'] = $pin.$difference;

}

About this page

Drupal version
Drupal 5.x, Drupal 6.x, Drupal 7.x
Audience
Programmers

Site Building Guide

Drupal’s online documentation is © 2000-2013 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License. Comments on documentation pages are used to improve content and then deleted.