IMEI validation function

Vladimir Gatev picture Vladimir Gatev · Jan 19, 2011 · Viewed 14.2k times · Source

Does anybody know a PHP function for IMEI validation?

Answer

rybo111 picture rybo111 · Jul 18, 2014

Short solution

You can use this (witchcraft!) solution, and simply check the string length:

function is_luhn($n) {
    $str = '';
    foreach (str_split(strrev((string) $n)) as $i => $d) {
        $str .= $i %2 !== 0 ? $d * 2 : $d;
    }
    return array_sum(str_split($str)) % 10 === 0;
}
function is_imei($n){
    return is_luhn($n) && strlen($n) == 15;
}

Detailed solution

Here's my original function that explains each step:

function is_imei($imei){
    // Should be 15 digits
    if(strlen($imei) != 15 || !ctype_digit($imei))
        return false;
    // Get digits
    $digits = str_split($imei);
    // Remove last digit, and store it
    $imei_last = array_pop($digits);
    // Create log
    $log = array();
    // Loop through digits
    foreach($digits as $key => $n){
        // If key is odd, then count is even
        if($key & 1){
            // Get double digits
            $double = str_split($n * 2);
            // Sum double digits
            $n = array_sum($double);
        }
        // Append log
        $log[] = $n;
    }
    // Sum log & multiply by 9
    $sum = array_sum($log) * 9;
    // Compare the last digit with $imei_last
    return substr($sum, -1) == $imei_last;
}