A whale that went viral swimming next to people on a Western Australian beach has died after becoming stuck in the sand.

Marine officials had spent several days trying to guide the elderly whale – which was injured and severely sunburned – back to deeper water.

Swimmers were filmed petting the 15-metre mammal while it was still alive on Saturday, as experts warned of dangers to both it and humans.

The whale carcass should be removed immediately to minimize the risks of shark sightings offshore.

This species of whale is the largest in the world and is considered a deep-sea feeder.

They are rarely found near the coast.

Authorities were concerned when they found the whale swimming dangerously close to Port Beach in Fremantle on Saturday.

“We realized very quickly that it was not in good shape,” said Mark Cugley, a spokesman for the state’s Department of Biodiversity, Conservation and Attractions.

The 30-tonne animal was returned to the sea, but wildlife experts warned it was at risk of becoming ill and interacting with it was dangerous.

The whale reappeared on Monday off the coast of Rockingham.

Authorities closed off access to the beach as they tried to save it.

Rescuers sprayed the animal with water to minimize the risk of blisters and sunburn, but it was too weak to return to the sea and its condition deteriorated further before it died on Tuesday morning.