As an academic/contrived task, I'd like to sort an indexed, 1-dimensional array so that the longest string is in the middle and its neighbouring elements should be the 2nd and 3rd longest and so on.
How can I alternate the position of the shortest strings working from the front and back of the array, and finish with the longest string(s) in the middle?
Sample input:
$array = ["Hello", "World", "this", "is", "a", "test"];
Desired result:
["a", "test", "Hello", "World", "this", "is"]
Explanation:
ais shortest and must be positioned firstisis 2nd shortest, so it takes last positiontestandthisare tied for 3rd shortest, alphabetize to break the tie which determines thattestcomes afteraandthiscomes beforeisHelloandWorldare tied for the longest strings, so alphabetize to break the tie and positionHelloaftertestandWorldbeforethis
A secondary example with an odd number of elements:
$array = ['hundreds', 'human', 'AI', 'replace', 'may', 'developers', 'soon'];
Desired result:
['AI', 'soon', 'replace', 'developers', 'hundreds', 'human', 'may']
Here is one way to do it (there's most likely a better solution):