Skip to content

Instantly share code, notes, and snippets.

@sergio-bobillier
Last active December 16, 2015 04:14
Show Gist options
  • Save sergio-bobillier/c619bfdc77e41cb4e926 to your computer and use it in GitHub Desktop.
Save sergio-bobillier/c619bfdc77e41cb4e926 to your computer and use it in GitHub Desktop.
Clean implementation of the Luhn algorithm in PHP
<?php
/** Validates a credit card number using the Luhn algorithm.
* http://en.wikipedia.org/wiki/Luhn_algorithm
*
* @param string $card_number The card number (without spaces, dots, or other
* special characters, only the numbers).
*
* @return boolean True if the number is valid, false otherwise.
*
*/
public function is_card_number_valid($card_number)
{
$digits = str_split($card_number);
$n = count($digits);
$sum = 0;
$dbl = false;
for($i = $n - 1; $i >= 0; $i--)
{
$digit = $digits[$i];
if($dbl)
{
$digit = $digit * 2;
if($digit >= 10) $digit -= 9;
}
$dbl = !$dbl;
$sum += $digit;
}
if($sum % 10 == 0)
return true;
return false;
}
@sergio-bobillier
Copy link
Author

A lot of Luhn Algorithm implementations on PHP around the net are unnecessarily complex, they do operations over the array keys or strange, inefficient ways of adding the numbers of the partial products. Here is a simple, and cleaner implementation.

Tested with credit card numbers generated with: http://www.getcreditcardnumbers.com/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment