Last active
June 6, 2017 14:31
-
-
Save CraigChilds94/6c710ca7699f7a92e7cf9015846cf19c to your computer and use it in GitHub Desktop.
DEA Number validation function https://en.wikipedia.org/wiki/DEA_number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if (!function_exists('dea_validate')) { | |
/** | |
* Validate a provided DEA number is valid. | |
* | |
* @param string $deaNumber | |
* @return boolean | |
*/ | |
function dea_validate($deaNumber) | |
{ | |
// Make sure we have the correct format. | |
if (preg_match('/^[A-Z9]{2}\d{7}$/', $deaNumber) !== 1) { | |
return false; | |
} | |
// Grab all characters in the number apart from the | |
// first one as we don't need it for calc. | |
$characters = array_slice(str_split((string)$deaNumber), 2); | |
// Grab the last digit as it's what we check. | |
$checkDigit = $characters[count($characters) - 1]; | |
// Our counters | |
$even = 0; | |
$odd = 0; | |
// Go through and sum up our digits. | |
foreach ($characters as $i => $character) { | |
if ($i > 5) { | |
break; | |
} | |
$digit = (int)$character; | |
if ($i % 2 == 0) { | |
$even += $digit; | |
} else { | |
$odd += $digit; | |
} | |
} | |
// Double the odd | |
$odd *= 2; | |
$sum = $even + $odd; | |
// Grab the check number from the sum. | |
$checksum = current(array_slice(str_split((string)$sum), 1)); | |
// The check digit needs to match our checksum. | |
return (int)$checkDigit === (int)$checksum; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment