Skip to content

Instantly share code, notes, and snippets.

@mazedlx
Last active November 12, 2021 08:20
Show Gist options
  • Save mazedlx/deecf1ed1ac98ee2aacd4bb058bfce1e to your computer and use it in GitHub Desktop.
Save mazedlx/deecf1ed1ac98ee2aacd4bb058bfce1e to your computer and use it in GitHub Desktop.
Code128 Checksum
<?php
const START = 'Ë';
const END = 'û';
const MOD = 103;
const OFFSET = 32;
const SPECIAL_OFFSET = 68;
const PACKAGE = '06';
function calcChecksum($value)
{
$digits = str_split($value);
$sum = array_reduce(
array_map(
function ($digit, $index) {
return (mb_ord($digit) - OFFSET) * ($index + 1);
},
$digits,
array_keys($digits)
),
function ($carry, $item) {
return $carry + $item;
},
MOD
);
if (($sum % MOD) + OFFSET > 126) {
return mb_chr(($sum % MOD) + OFFSET + SPECIAL_OFFSET);
}
return mb_chr(($sum % MOD) + OFFSET);
}
$file = fopen('/Users/maze/Downloads/bst1.csv', 'r');
while (($data = fgetcsv($file, 0, '|')) !== false) {
$id = PACKAGE . $data[2];
$checksum = calcChecksum($id);
echo $barcode = $id . '|' . START . $id . $checksum . END . PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment