PHP

Validate Credit Card (Luhn check)

admin by @admin ADMIN
29m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Apply the Luhn checksum algorithm to a credit card number. Strips spaces/dashes first. This validates the format — not whether the card actually exists or has funds.
PHP
Raw
<?php
function isValidLuhn(string $number): bool {
    $digits = preg_replace('/\D+/', '', $number);
    $len    = strlen($digits);
    if ($len < 12 || $len > 19) return false;

    $sum = 0;
    for ($i = 0; $i < $len; $i++) {
        $d = (int)$digits[$len - 1 - $i];
        if ($i % 2 === 1) {
            $d *= 2;
            if ($d > 9) $d -= 9;
        }
        $sum += $d;
    }
    return $sum % 10 === 0;
}

var_dump(isValidLuhn('4242 4242 4242 4242'));    // true (Stripe test Visa)
var_dump(isValidLuhn('4242-4242-4242-4243'));    // false (bad checksum)
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.