How and why was the earth formed?
The "how" was due to the nebular hypothesis and the "why" is not known.
The Earth formed as part of the formation of the Sun and planets in our system - this is called the nebular hypothesis (do a Socratic search on this same topic to see existing elaboration of this theory).
As to "why" it formed is probably due, to a large degree, to simple chance. Nebular gases were floating around in space and a passing comet or star may have started them swirling around. As they began to swirl, gravity began to sink most of the mass (as hydrogen) to the centre which became the Sun. The rest, or the leftovers, became the inner rocky planets (including Earth) and the outer gas giant planets.