3v4l.org

run code in 300+ PHP versions simultaneously
<? $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); }
Output for 7.1.26 - 7.1.33, 7.2.17 - 7.2.33, 7.3.0 - 7.3.31, 7.4.0 - 7.4.32, 8.0.0 - 8.0.12, 8.0.14 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.26, 8.4.1 - 8.4.13
<? $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); }
Output for 7.0.0 - 7.0.20, 7.1.0 - 7.1.20, 7.2.6, 7.3.32 - 7.3.33, 7.4.33, 8.0.13
1

preferences:
134.64 ms | 409 KiB | 5 Q