Is there a faster alternative to using array_unshift? I ran into a small programming example (reversing characters in an array) where I used array_unshift in a foreach() statement. When comparing it to a character set of 10,000 characters, it ran over 1,000 times slower than a direct array assignment routine!

Apparently, array_unshift is actually resizing the array, then moving all values down one position. So, the more characters you throw at it, the slower the process goes.

Any ideas how to get the same functionality without the performance hit?

    If you actually want to resize the array by adding an element to the front, then you actually want to resize the array by adding an element to the front.

    But now, what you are saying is that you used this to implement the reversal of an array. You then compared it to "a direct array assignment routine", and found that it was slower. Yet you ask "is there a faster alternative to using array_unshift". Obviously, you have already found one 😉

    That said, why not use [man]array_reverse/man?

      What laserlight said; but with the additional comment that [man]array_push[/man] or the equivalent operator doesn't require repeatedly reindexing the array.

        Write a Reply...