Skip to content

Commit

Permalink
Example code updated
Browse files Browse the repository at this point in the history
  • Loading branch information
Fejan Malek committed Aug 24, 2024
1 parent b5cc3cc commit 10d7e54
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions exercises/practice/luhn/.meta/example.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,31 @@

declare(strict_types=1);

function isValid($candidate)
function isValid(string $candidate): bool
{
$sanitizedCandidate = str_replace(" ", "", $candidate);

if (strlen($sanitizedCandidate) <= 1 || !ctype_digit($sanitizedCandidate)) {
return false;
}

$reversseCandidate = strrev($sanitizedCandidate);
$reverseCandidate = strrev($sanitizedCandidate);
$sum = 0;

for ($i = 1; $i < strlen($reversseCandidate); $i += 2) {
$digit = 2 * intval($reversseCandidate[$i]);
for ($i = 0; $i < strlen($reverseCandidate); $i++) {
$digit = intval($reverseCandidate[$i]);

if ($digit > 9) {
$digit -= 9;
// Double every second digit starting from the second position
if ($i % 2 != 0) {
$digit *= 2;

if ($digit > 9) {
$digit -= 9;
}
}

$sum += $digit;
$sum += intval($reversseCandidate[$i - 1]);
}

return $sum % 10 == 0;
return $sum % 10 === 0;
}

0 comments on commit 10d7e54

Please sign in to comment.