Convert ISBN10 to ISBN13 with PHP

January 1, 2007 • 1 min read

Since at the start of 2007 all books will no longer be using the ISBN10, we needed a way to convert all those ISBN10 numbers to the new ISBN13 (or EAN). There are no checks in the code to see if the number is numeric for example, but this should give you a good place to start.

function genchksum13($isbn)
{
   $isbn = trim($isbn);
   $tb = 0;
   for ($i = 0; $i <= 12; $i++)
   {
      $tc = substr($isbn, -1, 1);
      $isbn = substr($isbn, 0, -1);
      $ta = ($tc*3);
      $tci = substr($isbn, -1, 1);
      $isbn = substr($isbn, 0, -1);
      $tb = $tb + $ta + $tci;
   }

   $tg = ($tb / 10);
   $tint = intval($tg);
   if ($tint == $tg) { return 0; }
   $ts = substr($tg, -1, 1);
   $tsum = (10 - $ts);
   return $tsum;
}

function isbn10_to_13($isbn)
{
   $isbn = trim($isbn);
   if(strlen($isbn) == 12){ // if number is UPC just add zero
      $isbn13 = '0'.$isbn;}
   else
   {
      $isbn2 = substr("978" . trim($isbn), 0, -1);
      $sum13 = genchksum13($isbn2);
      $isbn13 = "$isbn2$sum13";
   }
   return ($isbn13);
}

// usage
echo isbn10_to_13('1234567890'); // returns ISBN13