PHP verifies that credit card numbers are valid using the Luhn algorithm

Source: Internet
Author: User
Tags ord
This article mainly introduces the PHP implementation through the LUHN algorithm to verify the validity of the credit card number, an example of the implementation of PHP Luhn algorithm and related application skills, with a certain reference value, the need for friends can refer to the next

In this paper, the method of verifying the validity of the credit card number by using the Luhn algorithm is described in PHP. The implementation method is as follows:

$numbers = "49927398716 49927398717 1234567812345678 1234567812345670"; foreach (Split (", $numbers) as $n)  echo" $n I S ", Luhntest ($n)? ' Valid ': ' Not valid ', ' </br> '; 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)%;    }  }     return $sum% 10 = = 0;}

Run results

49927398716 is valid49927398717 are not valid1234567812345678 are not valid1234567812345670 are 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 (' 49927398716 ', ' 49927398717 ', ' 1234567812345678 ', ' 1234567812345670 ') as $n) echo "$n is", Luhn_test ($n)? ' Valid ': ' Not valid ', ' </br>\n ';

The output is as follows

49927398716 is valid49927398717 are not valid1234567812345678 are not valid1234567812345670 are valid

Summary : The above is the entire content of this article, I hope to be able to help you learn.

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.