Ned's works but I don't know why indexing a higher number, $i++, after a splice doesn't cause problems as the array keeps getting resized with splice. Hope someone might know.
The answer lies in the result..
1 9 3 5 4 2
3 2 1 6 7 9
At i=0, the inner foreach loop takes out the first match set at index 0; and increments to 1.
9 3 5 4 2
2 1 6 7 9
Then at i=4, instead of taking out the first match set it takes out the second.
9 3 5 4
2 1 6 7