Implementation of the Luhn algorithm in PHP. Used in validation of credit card numbers and some national identification numbers.

4.0.1 2018-02-27 19:32 UTC


Build Status

This is an implementation of the Luhn Algorithm in PHP. The Luhn Algorithm is used to validate things like credit cards and national identification numbers. More information on the algorithm can be found at Wikipedia.


Install with Composer:

composer require nekman/luhn-algorithm


In order to instantiate a new instance of the library, use the factory:

use Nekman\LuhnAlgorithm\LuhnAlgorithmFactory;

$luhn = LuhnAlgorithmFactory::create();

You can find the public interface of the library in the LuhnAlgorithmInterface.

The Number class is a container class that holds the actual number and the check digit. It does no validation nor does it calculate the check digit. To simplify the process of validating a number you can use the named constructor Number::fromString() like this:

use Nekman\LuhnAlgorithm\Number;

// Assume $creditCard is from a form.
$number = Number::fromString($creditCard);

if ($luhn->isValid($number)) {
    // Number is valid.

Alternatively, if you want to calculate the checksum or check digit for a number:

use Nekman\LuhnAlgorithm\Number;

$number = new Number(12345);

$checksum = $luhn->calcChecksum($number);

$checkDigit = $luhn->calcCheckDigit($number);