This can be done with CSS, without any PHP code. Search for nth() child selector.
As regards the order of the elements, the best solution depends on what method you use to put the elements next to each other, if you use flexbox, you can use the order property. If you are using float, you can float the element left or right, all without having to change the order of the elements in the DOM.