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 git.master, git.master_jit, rfc.property-hooks
<? $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); }

This tab shows result from various feature-branches currently under review by the php developers. Contact me to have additional branches featured.

Active branches

Archived branches

Once feature-branches are merged or declined, they are no longer available. Their functionality (when merged) can be viewed from the main output page


preferences:
121.3 ms | 409 KiB | 5 Q