Choosing the ground you fight on is as important as any other factor, and has to be lumped in with all of the other parts of combat. The Romans were incredibly flexible and quite ingenious when it came to adapting to enemy methods, the testudo being a good example. It would seem that once the phalanxes advanced they came to uneven ground, and lost cohesion to the formation. At least, that is what was supposed to have happened at the Battle of Pydna. At that battle, Paullus ordered the legions into the gaps to attack the phalangites on their exposed flanks. At this range, within the killing reach of the sarissa, the Roman methods and superior shields and armour won by a long stroke (excuse pun
I honestly thought that the Romans would be able to get under the reach of the sarissas, thus rendering them useless, but apparently that wasn't the case. At the Battle of Cynocephalae, it seems to have been a desperate and inspired attack on the phalanxes exposed and vulnerable rear that turned the tide and won the day for Rome. The sarissas would have been even useful then, had the Romans understood that their being raised was the sign of surrender. Alas, they didn't.
Polybius also asserts that once the phalanx is broken in any way it is left open for infiltration by more agile and flexible Romans, who can actually wade in and cut it down from within. Phalanx vs Legion