Michael Phelps’s unprecedented Olympic career ended Saturday night with one last medal: a gold in the 4x100-meter medley relay that brought fans at the Aquatics Center to their feet and left Phelps with 22 career medals, 18 of them gold.

The United States foursome of Matt Grevers on backstroke, Brendan Hansen on breaststroke, Phelps in the butterfly and Nathan Adrian as the freestyle anchor won in 3 minutes, 29.35 seconds — nearly two full seconds ahead of silver medalists Japan (3:31.26). Australia took bronze in 3:31.58.

But the result was hardly a given when Phelps dove into the water for his butterfly leg with the Americans trailing by 0.21 of a second.

At the 50-meter mark of his swim, the Americans trailed by 0.26 of a second. But Phelps completely turned that around with a stunning second half of his race, destroying Japan’s Takeshi Matsuda and handing Adrian a lead of 0.26 of a second.

“I could probably sum it up in a couple words,” Phelps said of his career accomplishments. “I did it.”

The race followed an equally dramatic world-record breaking performance from the U.S. women.

The team swimmers who had each won individual gold medals at these Games: Missy Franklin in the backstroke, Rebecca Soni in the breaststroke, Dana Vollmer in the butterfly and Allison Schmitt in the freestyle. Three of them set world records, with Schmitt the only exception.

Together they produced another sublime performance. Their time of 3:52.05 beat the old world record, set by China at the 2009 world championships, by 0.14 of a second. Australia finished second in 3:54.02 and Japan (3:55.73) took bronze.

The U.S. men’s relay team was heavily favored because it featured not only Phelps — who won one of his gold medals in the 100 butterfly on Friday — but gold-medal winners Grevers and Adrian. Hansen has represented the U.S. on the breaststroke leg in each of the past three Olympics, and he won bronze in the 100 breast earlier in the meet.

Phelps’s meet here started poorly, with a fourth-place finish in the 400-meter individual medley, the first time he had failed to medal in an event since he made his Olympic debut as a 15-year-old at the 2000 Sydney Games. But he finished with six medals in his remaining six events, including golds in his final four races: the 4×200-meter freestyle relay, the 200 individual medley, the 100 butterfly and the medley relay.

“I’ve been able to do everything I’ve wanted,” Phelps said. “I’ve been able to put my mind to the goals that I wanted to achieve. ... If you can say that about your career, there’s no need to move foward.”

Matt Brooks contributed to this report.