PHP: Best credit card checker algorithm

By Fernando Katsukawa, 3 December, 2022

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

About the Author

Profile picture for user fkatsukawa

Fernando Katsukawa is a certified senior backend developer, who have been worked with Drupal in the last 12 years and counting...

Saved your precious time? Use the cup below to buy me a coffee!
buy me a coffee - cup