You should also extract the count() part from the foreach statement here into a separate variable (as it was before).