[Fix] Avoid recalculating count() for each iteration.

Since the value of `count($segments)` will never change during the method execution, cache it to avoid recalculating it for each iteration of the loop.