/*///////////////////////////////////////////////////////////////
Calculate UPC (UPC-A), PHP, 2010-12-10
Artix, master@7masterov.ru, icq:53666599, skype:artixmaster
* Error in code? Nothing is perfect!
* Free source for free Linux, use it for free!
* Please, do not remove this comment!
///////////////////////////////////////////////////////////////*/
function genUPC() {
$code = ''; while(strlen($code)<11) $code.=rand(0,9);
$s1 = 0; $s2 = 0;
for($i=0;$i<strlen($code);$i+=2) {
$s1+=intval($code{$i});
if (isset($code{$i+1})) $s2+=intval($code{$i+1});
}
$s1*=3;
$r = (10-($s1+$s2) % 10) % 10;
$s=$code.$r;
return $s;
}
function checkUPC($code) {
if (strlen($code)==12) {
$s1=0; $s2=0;
for($i=0;$i<strlen($code);$i+=2) {
$s1+=intval($code[$i+1]);
$s2+=intval($code[$i]);
}
$s2*=3;
$check = ($s1+$s2) % 10;
if ($check==0) return true;
}
return false;
}
$x = genUPC();
echo checkUPC($x)? "$x correct\n" : "$x incorrect!\n";
Справочник алгоритмов v0.05 © 2007-2025 Igor Salnikov aka SunDoctor