Africa Cup of Nations holders Ivory Coast mounted a late comeback to beat Gabon and top Group F on goals scored ahead of Cameroon.
The Elephants trailed 2-0 by the 21st minute, but Jean-Philippe Krasso pulled one back just before the break by tapping in Wilfried Zaha’s square ball.
The Ivorians rarely threatened in the second half until Aston Villa forward Evann Guessand headed in a corner to equalise with six minutes remaining and set up a frantic finale.
Bazoumana Toure then completed the turnaround in the first of five added minutes, with the wideman’s diving header from Christopher Operi’s left-wing cross sparking wild celebrations.
Yan Diomande thought he had made it 4-2 from a late counter-attack, but the goal was ruled out for offside earlier in the move after a check by the video assistant referee (VAR).
With the Elephants drawing until late on, Cameroon had been set to top the group by two points courtesy of their 2-1 win over Mozambique.
Ivory Coast will now face Burkina Faso in the last 16 in Marrakesh on Tuesday, 6 January (19:00 GMT), with the victory sparing them a more challenging route to the final.