UK troops will leave Iraq in the second half of 2009, Prime Minister Gordon Brown has confirmed during a surprise visit to the country.