Friday, October 7, 2011

Generate a valid 12 digit UPC number with PHP

As NEXTAG was complaining about random 8 digit product ID in the feed of one of our clients, we were urged by their feed debugger to use UPC-A code for that field.

As our clients products did not have UPC codes we put together this little function based on UPC-A description on wikipedia.


function UPC() {

$odd_sum = $even_sum = 0;

for ($i = 1; $i < 12; $i++) {
$digits[$i] = rand(0,9);
if($i % 2 == 0)
$even_sum += $digits[$i];
else
$odd_sum += $digits[$i];
}

$digits[$i] = 10 - ((3 * $odd_sum + $even_sum) % 10);

return implode('',$digits);
}

echo UPC();


Check this website to validate PHP generated UPC code