How does PHP verify whether there is a problem with the credit card number? This article mainly introduces the PHP implementation of the Luhn algorithm to verify whether the credit card number is valid, and analyzes the implementation of the Luhn algorithm in PHP and related application skills through examples. I hope to be helpful.
The specific implementation method is as follows:
$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; }
49927398716 is valid 49927398717 is not valid 1234567812345678 is not valid 1234567812345670 is valid
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";
49927398716 is valid 49927398717 is not valid 1234567812345678 is not valid 1234567812345670 is valid
Related recommendations:
php Regular expression code to determine whether the IP is legal
php Function code to determine whether the visitor is a search engine spider
PHP Determine whether the client is IOS or Android
The above is the detailed content of PHP verification credit card number example. For more information, please follow other related articles on the PHP Chinese website!