Algorithm Fundamental php Programming
LUHN Algorithm to Validate Credit Card & Example & Implementation with Programming Example
January 21, 2016
0

The LUHN Algorithm is used to distinguish valid Credit Card numbers that is random selection of digits.

Credit Card numbers that can be validated by the LUHN Algorithm have numbers that pass the following test:

1. Reverse the order of the digits in the number.
2. Take the first, third, … and every other odd digit in the reversed digits and sum them to form the partial sum s1
3. Taking the second, fourth … and every other even digit in the reversed digits:
i. Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits
ii. Sum the partial sums of the even digits to form s2

4. If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.

For example, if the trial number is 49927398716:

Reverse the digits:
61789372994
Sum the odd digits:
6 + 7 + 9 + 7 + 9 + 4 = 42 = s1
The even digits:
1, 8, 3, 2, 9
Two times each even digit:
2, 16, 6, 4, 18
Sum the digits of each multiplication:
2, 7, 6, 4, 9
Sum the last:
2 + 7 + 6 + 4 + 9 = 28 = s2

s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test

 

PHP Sample Code:

<?php

$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) % 10;

}
}
return $sum % 10 == 0;
}

?>

 

Sample Code Output:

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

And a more concise example using PHP core methods:

<?php

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”;

?>

PHP Code Output:
49927398716 is valid
49927398717 is not valid
1234567812345678 is not valid
1234567812345670 is valid

 

About author

ZERIN

Steganography

The LUHN Algorithm is used to distinguish valid Cr...

Read more

How to Code Signing to Your Java Project

The LUHN Algorithm is used to distinguish valid Cr...

Read more

Laravel Error Fix: Laravel 5 InvalidArgumentException in FileViewFinder.php line 137: View [.admin] not found

The LUHN Algorithm is used to distinguish valid Cr...

Read more

There are 0 comments

Leave a Reply

Your email address will not be published. Required fields are marked *