<?php
class NIP
{
private const WEIGHTS = [6, 5, 7, 2, 3, 4, 5, 6, 7];
private const NIP_MODULO = 11;
private const INVALID_CHECKSUM = 10;
public static function validate(string $nip): bool
{
$value = preg_replace('/[\s-]/', '', $nip);
if ('0000000000' === $value || !preg_match('/^\d{10}$/', $value)) {
return false;
}
$checkSum = self::getChecksum($value);
if (self::INVALID_CHECKSUM === $checkSum || $checkSum !== ((int) (substr($value, -1)))) {
return false;
}
return true;
}
private static function getChecksum(string $nip): int
{
$sum = 0;
foreach (self::WEIGHTS as $key => $weight) {
$sum += $weight * ((int) $nip[$key]);
}
return $sum % self::NIP_MODULO;
}
}
$nip_numbers = array(
"1234563218",
"9876543290",
"5627384901",
"9012345678",
"6748392105",
"4382905671",
"7591234890",
"8901234765",
"3210987654",
"9876504321"
);
$c = new NIP();
foreach ($nip_numbers as $a) {
var_dump($c->validate($a));
}
preferences:
24.45 ms | 407 KiB | 5 Q