Foam in a fuel cell prevents a concentration of the fuel vapor plus air mixture which significantly reduces the probability that the fuel cell will explode in case of a fire. While displacing a very small amount of fuel the foam prevents sloshing of the fuel.

Fuel Cell Foam Or No Foam
Fuel cell foam purpose. This keeps the air mixture in the cell to rich to explode. The foam is not connected in any way to the cell bladder. So you can gain access to the interior of the cell. When a vehicle abruptly changes directions safety foam helps to reduce surge or fuel sloshing inside of the fuel cell creating a baffling effect. An important purpose or function of the safety foam in a fuel cell is to stop a flame front from advancing therefore helping to eliminate the possibility of explosion. Most fuel cells have a simple can and lid.
As we know gasoline wont burn if the mixture of air to fuel is too rich or too lean. The foam sits inside the cell and is stacked. The main purpose of foam is to displace air in the cell. The lid bolts on. If the cell ever did get punctured and if a fire started the porous foam baffling would help to prevent the fuel inside the cell from exploding. Reducing the amount of foam in a fuel cell either by not putting it in to the eight inch mandated height or by carving out hollows in the interior of the foam creates a very highly flammable pocket of fuel vapor and a major safety hazard.
A secondary benefit the foam affords is its ability to prevent flash back explosions. The fuel cell foam baffling can be thought of as a big sponge inside the fuel cell. By preventing sloshing the foam keeps the fuel de aerated which improves fuel delivery and also insures constant delivery of fuel to the pickup. A happy side benefit is that the baffling also helps to reduce fuel slosh which would otherwise affect handling.