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;

}