Collective sensing and phenotypic diversification aid response to environmental fluctuations