选择语言 :

 Core_Valid::luhn

Validate a number against the Luhn (mod10) formula.

boolean Core_Valid::luhn( string $number )

参数列表

参数 类型 描述 默认值
$number string Number to check
返回值
  • boolean
File: ./core/classes/valid.class.php
public static function luhn($number)
{
    // Force the value to be a string as this method uses string functions.
    // Converting to an integer may pass PHP_INT_MAX and result in an error!
    $number = (string)$number;

    if (!ctype_digit($number))
    {
        // Luhn can only be used on numbers!
        return false;
    }

    // Check number length
    $length = strlen($number);

    // Checksum of the card number
    $checksum = 0;

    for($i = $length - 1; $i >= 0; $i -= 2)
    {
        // Add up every 2nd digit, starting from the right
        $checksum += substr($number, $i, 1);
    }

    for($i = $length - 2; $i >= 0; $i -= 2)
    {
        // Add up every 2nd digit doubled, starting from the right
        $double = substr($number, $i, 1) * 2;

        // Subtract 9 from the double where value is greater than 10
        $checksum += ($double >= 10) ? ($double - 9) : $double;
    }

    // If the checksum is a multiple of 10, the number is valid
    return ($checksum % 10 === 0);
}