MANILA — The Philippines on Monday declared an end to months of fighting against Islamic State-inspired militants in the southern city of Marawi, saying that the last “stragglers” had been killed in a firefight with the army.

The announcement came on the same day that the American defense secretary, Jim Mattis, arrived in the Philippines for an annual meeting of defense ministers in the region.

Defense Secretary Delfin Lorenzana of the Philippines said more than 40 militants, including at least five foreigners, had been killed when Philippine soldiers stormed a building in Marawi where they were holed up. Forty-two bodies were recovered, said Mr. Lorenzana, who called the militants “the last group of stragglers” in the monthslong siege.