Validate EAN with PHP

/**
 * Validates EAN-13.
 *
 * @see    https://wpcodebook.com/validate-ean-php/
 * @param  string $ean EAN to validate
 * @return bool
 */
function wpcodebook_is_valid_ean13( $ean ) {

	// Length
	if ( 13 != strlen( $ean ) ) {
		return false;
	}

	// Only digits
	if ( ! preg_match( "/^[0-9]+$/", $ean ) ) {
		return false;
	}

	// The check digit
	$check    = substr( $ean, -1 );
	$ean      = substr( $ean, 0, -1 );
	$sum_even = 0;
	$sum_odd  = 0;
	$even     = true;

	while ( strlen( $ean ) > 0 ) {
		$digit = substr( $ean, -1 );
		if ( $even ) {
			$sum_even += 3 * $digit;
		} else {
			$sum_odd  += $digit;
		}
		$even = ! $even;
		$ean  = substr( $ean, 0, -1 );
	}

	$sum            = $sum_even + $sum_odd;
	$sum_rounded_up = ceil( $sum / 10 ) * 10;
	$result         = ( $check == ( $sum_rounded_up - $sum ) );

	return $result;
}

Leave a Comment