PHP uses the Luhn algorithm to verify whether the credit card number is valid

Source: Internet
Author: User
This article describes how to verify the validity of credit card numbers through the Luhn algorithm in PHP. The example shows how to implement the Luhn algorithm and related application skills in php, which has some reference value, for more information about how to use the Luhn algorithm to verify the validity of credit card numbers, see the example in this article. Share it with you for your reference. The specific implementation method is as follows:

$numbers = "49927398716 49927398717 1234567812345678 1234567812345670";foreach (split(' ', $numbers) as $n)  echo "$n is ", luhnTest($n) ? 'valid' : 'not valid', '
'; function luhnTest($num) { $len = strlen($num); for ($i = $len-1; $i >= 0; $i--) { $ord = ord($num[$i]); if (($len - 1) & $i) { $sum += $ord; } else { $sum += $ord / 5 + (2 * $ord) % 10; } } return $sum % 10 == 0;}

Running result

49927398716 is valid49927398717 is not valid1234567812345678 is not valid1234567812345670 is valid

The following is a more concise code:

The code is as follows:

Function luhn_test ($ num ){
$ Str = '';
Foreach (array_reverse (str_split ($ num) as $ I => $ c) $ str. = ($ I % 2? $ C * 2: $ c );
Return array_sum (str_split ($ str) % 10 = 0;
}
Foreach (array ('20160301', '20160301', '20160301', '20160301') as $ n)
Echo "$ n is", luhn_test ($ n )? 'Valid': 'not valid ',"
\ N ";

The output result is as follows:

49927398716 is valid49927398717 is not valid1234567812345678 is not valid1234567812345670 is valid

I hope this article will help you with php programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.