PDA

Click to See Complete Forum and Search --> : Validate UPC - Create valid UPC


dclamp
Nov 27th, 2009, 08:31 PM
This class i created will validate a supplied UPC code.

Class

<?php
class upcvalidator {

function createCheckDigit($code) {
if ($code) {
for ($counter=0;$counter<=strlen($code)-1;$counter++) {
$codearr[]=substr($code,$counter,1);
}

for ($counter=0;$counter<=count($codearr)-1;$counter++) {
if ( $counter&1 ) {
$evensum = $evensum + $codearr[$counter];
} else {
$oddsum = $oddsum + $codearr[$counter];
}
}

$oddsum = $oddsum *3;
$oddeven = $oddsum + $evensum;

for ($number=0;$number<=9;$number++) {
if (($oddeven+$number)%10==0) {
$checksum = $number;
}
}

return $checksum;
} else {
return false;
}
}

function validateUPC($upc) {
if ($upc!="") {
$checkdigit = substr($upc, -1);
$code = substr($upc, 0, -1);

$checksum = $this->createCheckDigit($code);
if ($checkdigit == $checksum) {
return true;
} else {
return false;
}
} else {
return false;
}
}

function createUPC($code) {
if ($code) {
$checkdigit = $this->createCheckDigit($code);
$upc = $code . $checkdigit;

return $upc;
} else {
return false;
}
}
}
?>


Functions

createCheckDigit($code) - When supplied with an 11 digit code, will return the check digit. No practical use, used for the class.

createUPC($code) - When supplied with an 11 digit code, will return with the valid check digit amended to the code.

validateUPC($upc) - When supplied with the 12 digit UPC, will validate the UPC code.

Example

Create Class

require_once ("$class.upcvalidator.php");
$upcvalidate = new upcvalidator;


validateUPC()

//valid upc
$upc = 639382000393;
$validate = $upcvalidate->validateUPC($upc); //returns true

//invalid upc
$upc = 123456789123;
$validate = $upcvalidate->validateUPC($upc); //returns false



createUPC()

$code = 12345678900; // 11 digit code
$upc = $upcvalidate->createUPC($code);
echo $upc; //returns 123456789005
//Notice the 5. 5 is the valid check digit.

dclamp
Nov 27th, 2009, 08:39 PM
Here are the attachments