Web Development 1 min read 115 words

How to validate an EAN13 code

ES
How to validate an EAN13 code

EAN13 codes are composed of 13 digits, where the last one is a check digit.

Using the following PHP function, you can verify if an EAN is correctly formed:

function isValidEAN( $ean ){
	$ean =(string)$ean;
	// Must have 13 characters
	if ( strlen( $ean ) != 13 ) {
		return false ;
	}
	$even_sum = $ean{1} + $ean{3} + $ean{5} + $ean{7} + $ean{9} + $ean{11};
	$even_sum_three = $even_sum * 3;
	$odd_sum = $ean{0} + $ean{2} + $ean{4} + $ean{6} + $ean{8} + $ean{10};
	$total_sum = $even_sum_three + $odd_sum;
	$next_ten = (ceil($total_sum/10))*10;
	$check_digit = $next_ten - $total_sum;
	$valid = substr( $ean, 0, 12 ) . $check_digit ;
	return  ( $ean  == $valid ) ;
}