PHP Language You are to write a function that takes a string

PHP Language

You are to write a function that takes a string as an argument, and returns true or false if the string passes the Luhn test.
The Luhn test will determine if the string is a valid credit card number of not.

Click the link to the right to get an outline of the Luhn php code.   -   Luhn Outline
All you will need to do is complete the validCard function.

The Luhn Algorithm

From the rightmost digit, and moving left, double the value of every second digit.
If the result of this doubling operation is greater than 9 (e.g., 8 × 2 = 16), then add the digits of the product (e.g., 16: 1 + 6 = 7, 18: 1 + 8 = 9)

Take the sum of all the digits.

If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; else it is not valid.


7 + 9 + 9 + 4 + 7 + 6 + 9 + 7 + 7 + 2 + 1 = 68
68 % 10 = 8
Since 68 %10 does not = 0, this is not a valid credit card number.

You will need the following php string functions to accomplish this.
strlen - returns the length of a string.
is_numeric - returns true or false if string is numeric
substr - returns a portion of the string.

Account number 7 9 9 2 7 3 9 8 7 1 1
Double every other 7 18 9 4 7 6 9 16 7 2 1
Sum digits 7 9 9 4 7 6 9 7 7 2 1

Solution

<?php
function validateCreditCardNumber($input)
{
// remove any non-digits
$input=preg_replace(\'/\\D/\', \'\', $input);
$input_length=strlen($input);
$parity=$input_length % 2;
// Apply Luhn\'s algorithm on every digit
$sum=0;
for ($i=0; $i<$input_length; $i++)
{
$current_digit=$input[$i];
if ($i % 2 == $parity)
{
$current_digit*=2;
if ($current_digit > 9)
$current_digit-=9;
}
$sum+=$current_digit;
}
return ($sum % 10 == 0) ? TRUE : FALSE;
}
?>

PHP Language You are to write a function that takes a string as an argument, and returns true or false if the string passes the Luhn test. The Luhn test will de

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site