Backport foreach loop to 1.4.X branch