Portugal will play Croatia in the last 16 at Euro 2016 after Cristiano Ronaldo scored twice in a six-goal thriller against Hungary in Lyon.
A Zoltan Gera half-volley put Hungary in front but Ronaldo set up Nani to fire in an equaliser before the break.
Two deflected Balazs Dzsudzsak strikes twice restored Hungary's lead early in the second half, but a Ronaldo flick and header levelled on each occasion.
Hungary progress as Group F winners, with Portugal through in third place.
Portugal had been on course to play England in the last 16 as they occupied second place in the group at the final whistle in Lyon, but it was Iceland who claimed the runner-up spot with a dramatic injury-time winner against Austria in Paris.
Portugal, who would have crashed out had they lost to Hungary, have now reached the knockout stage in all seven of their European Championship appearances.
Hungary will play the second-placed team from Group E - Belgium, Sweden or Republic of Ireland.
Unfancied Hungary have emerged as one of the feel-good stories of the Euros and have advanced from the group stage of a major tournament for the first time since the 1966 World Cup.
They conceded 63.2% of possession to Portugal but they scored three goals and caused Portugal's defence plenty of problems, even though manager Bernd Storck did not play four players on yellow cards.
They went ahead when 37-year-old former West Brom and Fulham midfielder Gera chested down a half-cleared corner before drilling home from 25 yards, while a free-kick and left-footed strike from Dzsudzsak went in off Andre Gomes and Nani respectively.
Akos Elek and Gergo Lovrencsics also went close, while a shot from Adam Szalai hit the post in a pulsating game.