The Luhn Algorithm is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, and others. This documentation provides an overview of the Luhn Algorithm implementation in PHP, including examples and use cases.
You can install the package via composer:
composer require designbycode/luhn-algorithm
To validate a value using the Luhn Algorithm, create an instance of the LuhnAlgorithm class and call the isValid method:
$luhn = new LuhnAlgorithm();
$isValid = $luhn->isValid('79927398713'); // returns true
The isValid method returns true
if the value is valid, and false
otherwise.
To generate a check digit for a given value, call the generate
method:
$luhn = new LuhnAlgorithm();
$generatedCheckDigit = $luhn->generate('7992739871'); // returns '79927398713'
The generate
method returns the generated value including the check digit.
To strip the check digit from a given value, call the withoutDigit
method:
$luhn = new LuhnAlgorithm();
$valueWithoutDigit = $luhn->withoutDigit('79927398713'); // returns '7992739871'
The withoutDigit
method returns the value without the check digit.
To validate a value and suggest the correct check digit if invalid, call the validateAndSuggest
method:
$luhn = new LuhnAlgorithm();
$result = $luhn->validateAndSuggest('79927398712'); // returns ['isValid' => false, 'uggestedDigit' => '3']
The validateAndSuggest
method returns an array containing isValid
and suggestedDigit
values.
The Luhn Algorithm is commonly used to validate credit card numbers. You can use the isValid
method to check if a credit card number is valid:
$luhn = new LuhnAlgorithm();
$isValid = $luhn->isValid('4242424242424242'); // returns true
The Luhn Algorithm can also be used to validate IMEI numbers. You can use the isValid
method to check if an IMEI number is valid:
$luhn = new LuhnAlgorithm();
$isValid = $luhn->isValid('352656091234567'); // returns true
You can use the generate
method to generate check digits for various identification numbers, such as customer IDs or product codes:
$luhn = new LuhnAlgorithm();
$generatedCheckDigit = $luhn->generate('CUSTOMER1234'); // returns 'CUSTOMER12345'
The Luhn Algorithm implementation throws an InvalidArgumentException
if the input value is empty or invalid. You can catch this exception to handle errors:
try {
$luhn = new LuhnAlgorithm();
$luhn->isValid('');
} catch (InvalidArgumentException $e) {
echo 'Error: '. $e->getMessage();
}
The Luhn Algorithm implementation in PHP provides a simple and efficient way to validate and generate check digits for various identification numbers. By following this documentation, you can easily integrate the Luhn Algorithm into your PHP applications.
composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.