PHP Luminova: Generate and Validate Luhn Check Digits
Calculate a Luhn checksum, generate a check digit, and check identifiers that use the Luhn algorithm.
Use Luhn when an identifier follows the Luhn checksum convention. Keep the input as a string to preserve leading zeroes. Check the identifier’s required format and length separately. A valid checksum only confirms the arithmetic check.
Usage
use Luminova\Utility\Luhn;
$reference = Luhn::generate('7992739871');
echo $reference; // 79927398713
var_dump(Luhn::isValid($reference)); // bool(true)Class Definition
- Full namespace:
Luminova\Utility\Luhn - This class is a concrete class.
Methods
sum
Calculate the weighted sum from right to left, doubling alternating digits and subtracting nine from doubled values above nine. Non-digit characters are ignored.
public static function sum(string $number): intParameters:
| Parameter | Type | Description |
|---|---|---|
$number | string | Input string containing digits. |
Return:
int - Weighted checksum total.
isValid
Check whether the weighted sum is divisible by ten. Because input with no digits has a sum of zero, validate the expected input format before calling this method.
public static function isValid(string $number): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$number | string | Complete identifier including its check digit. |
Return:
bool - true when the weighted sum is divisible by ten.
digit
Calculate the digit to append to a base number.
public static function digit(string $number): intParameters:
| Parameter | Type | Description |
|---|---|---|
$number | string | Base number without the check digit. |
Return:
int - Check digit from 0 to 9.
generate
Append a calculated check digit to the original input. Any formatting in the input remains in the result.
public static function generate(string $number): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$number | string | Base number without the check digit. |
Return:
string - Original string followed by the check digit.