Changing loop conditions in order to avoid an access to undef array offset