PHP implementation through the LUHN algorithm to check whether the card card number is effective _php skills

Source: Internet
Author: User
Tags ord

The example of this article tells the PHP implementation through the LUHN algorithm to verify the validity of the credit card card number method. Share to everyone for your reference. The implementation methods are as follows:

$numbers = "49927398716 49927398717 1234567812345678 1234567812345670";
foreach (Split (', $numbers) as $n)
  echo "$n is", 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% = 0;
}

Run results

49927398716 is valid 49927398717 are not valid 1234567812345678 are not valid
1234567812345670 are
valid

Here's a more concise code:

Copy Code code 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 valid 49927398717 are not valid 1234567812345678 are not valid
1234567812345670 are
valid

I hope this article will help you with your PHP program design.

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.