Skip to content

Instantly share code, notes, and snippets.

@Komche
Last active August 2, 2019 13:59
Show Gist options
  • Save Komche/93dac0f4590722369f00398b76722b09 to your computer and use it in GitHub Desktop.
Save Komche/93dac0f4590722369f00398b76722b09 to your computer and use it in GitHub Desktop.
This function check if the number is a valid luhn
<?php
/**
* @param string $val
* @return bool
*/
function checkIsValidLuhn($val)
{
$i = 0;
$arr = str_split($val);
$arr = array_reverse($arr);
foreach ($arr as &$value) {
$i++;
if (($i % 2) == 0) {
$value = $value * 2;
if ($value > 9) {
$arr_s = str_split($value);
$value = array_sum($arr_s);
} else {
$value = $value;
}
}
}
if ((array_sum($arr) % 10) === 0) {
echo ('code is valid');
return true;
} else {
echo ('code is not valid');
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment