These days I was developing some credit card features, and I was looking for a credit card checker. So I found the Luhn algorithm, also known as the modulus 10 or mod 10 algorithm.
About the Luhn algorithm: A simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, Canadian Social Insurance Numbers.
Check below the function to valid credit card using Luhn algorithm:
/**
* Check if credit card number is valid.
*
* The Luhn algorithm or Luhn formula, also known as the "modulus 10" or
* "mod 10" algorithm, is a simple checksum formula used to validate a variety
* of identification numbers, such as credit card numbers.
*
* @param string $credit_card_number
* Credit card number to be validated.
*
* @return bool
* TRUE if credit card number is valid, FALSE otherwise.
*/
function creditCardNumberIsValid(string $credit_card_number): bool {
$sum = 0;
$flag = 0;
for ($i = strlen($credit_card_number) - 1; $i >= 0; $i--) {
$add = $flag++ & 1 ? $credit_card_number[$i] * 2 : $credit_card_number[$i];
$sum += $add > 9 ? $add - 9 : $add;
}
return $sum % 10 === 0;
}