Skip to content

Instantly share code, notes, and snippets.

@lauriii
Last active October 21, 2022 12:40
Show Gist options
  • Save lauriii/3cb3b32ad86c271ebc681012855ce529 to your computer and use it in GitHub Desktop.
Save lauriii/3cb3b32ad86c271ebc681012855ce529 to your computer and use it in GitHub Desktop.
Y-Tunnus tarkistus (Finnish business ID validator)
<?php
function validate_company_id($company_id) {
// Some old company id's have only 6 digits. They should be prefixed with 0.
if (preg_match("/^[0-9]{6}\\-[0-9]{1}/", $company_id)) {
$company_id = '0' . $company_id;
}
// Ensure that the company ID is entered in correct format.
if (!preg_match("/^[0-9]{7}\\-[0-9]{1}/", $company_id)) {
return FALSE;
}
list($id, $checksum) = explode('-', $company_id);
$checksum = (int) $checksum;
$total_count = 0;
$multipliers = [7, 9, 10, 5, 8, 4, 2];
foreach ($multipliers as $key => $multiplier) {
$total_count = $total_count + $multiplier * $id[$key];
}
$remainder = $total_count % 11;
// Remainder 1 is not valid.
if ($remainder === 1) {
return FALSE;
}
// Remainder 0 leads into checksum 0.
if ($remainder === 0) {
return $checksum === $remainder;
}
// If remainder is not 0, the checksum should be remainder deducted from 11.
return $checksum === 11 - $remainder;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment