<?
$upc = "5901234123457"; //valid
//"889296852094";
//"5901244123457"; //invalid
//"889295852094";
echo isValidBarcode($upc) ? 1 : 0;
function isValidBarcode($barcode) {
$barcode = trim($barcode);
$bcLen = strlen($barcode);
//If value is not numeric, it is not valid.
if (!is_numeric($barcode) && ($bcLen == 12 || $bcLen == 13)) return false;
//set empty variables
$even_sum = $odd_sum = 0;
preg_match_all('/(\w)(\w)/',$barcode,$oddEven);
$even_sum = array_sum($oddEven[1]);
// If you have an odd number of chars in the barcode, this regex will not account for the last char.
// If you have an even number of chars, you will still need to pop the last char off manually.
if($bcLen % 2 === 0) array_pop($oddEven[2]);
$odd_sum = array_sum($oddEven[2]);
//Multiply even_sum by 3, and then add odd_sum to it.
$total_sum = $even_sum * 3 + $odd_sum;
//get highest multiple of 10 of total_sum.
$next_ten = ceil($total_sum / 10) * 10;
//Subtract highest multiple of 10 from total_sum to get check_digit.
$check_digit = $next_ten - $total_sum;
//if check_digit is equal to the last digit in the barcode, it is valid.
return $check_digit == substr($barcode, $bcLen-1);
}
<?
$upc = "5901234123457"; //valid
//"889296852094";
//"5901244123457"; //invalid
//"889295852094";
echo isValidBarcode($upc) ? 1 : 0;
function isValidBarcode($barcode) {
$barcode = trim($barcode);
$bcLen = strlen($barcode);
//If value is not numeric, it is not valid.
if (!is_numeric($barcode) && ($bcLen == 12 || $bcLen == 13)) return false;
//set empty variables
$even_sum = $odd_sum = 0;
preg_match_all('/(\w)(\w)/',$barcode,$oddEven);
$even_sum = array_sum($oddEven[1]);
// If you have an odd number of chars in the barcode, this regex will not account for the last char.
// If you have an even number of chars, you will still need to pop the last char off manually.
if($bcLen % 2 === 0) array_pop($oddEven[2]);
$odd_sum = array_sum($oddEven[2]);
//Multiply even_sum by 3, and then add odd_sum to it.
$total_sum = $even_sum * 3 + $odd_sum;
//get highest multiple of 10 of total_sum.
$next_ten = ceil($total_sum / 10) * 10;
//Subtract highest multiple of 10 from total_sum to get check_digit.
$check_digit = $next_ten - $total_sum;
//if check_digit is equal to the last digit in the barcode, it is valid.
return $check_digit == substr($barcode, $bcLen-1);
}