Convert UPC-E Barcodes to UPC-A with PHP

Recently I had the need to convert 8 digit UPC-E barcodes to 12 digit UPC-A barcodes for an inventory app I was working on.

After lots of Googling, I found this one written in Visual Basic: http://upcdata.info/?action=e2a

And did my best to convert it to PHP. The results are below. Let me know if it does/doesn’t work for you.

      function fixedUPC($upc) {
 
           $valid_digits = substr($upc,1,6);
 
           $last_digit = substr($valid_digits,-1);
 
           switch($last_digit) {
               case "0":
               case "1":
               case "2":
                   $upc_a = substr($valid_digits,0,2) . $last_digit
                       . "0000" . substr($valid_digits,2,3);
                   break;
               case "3":
                   $upc_a = substr($valid_digits,0,3)
                           . "00000" . substr($valid_digits,3,2);
                   break;
               case "4":
                   $upc_a = substr($valid_digits,0,4)
                           . "00000" . substr($valid_digits,5,1);
                   break;
               default:
                   $upc_a = substr($valid_digits,0,5)
                           . "0000" . substr($valid_digits,5,1);
           }
           return substr($upc,0,1) . $upc_a . substr($upc,-1);
       }
This entry was posted in PHP. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" cssfile="">