Don't see any reasons that you should try to rewrite this function to speed up the process.... If it takes 5 seconds to process this function then yeah, you should think other way to write it, but you are talking about the speed in miliseconds I think....
There are things that help you to write a better code.
PHP offers different ways to write, for example, a looping an array. There are while(), foreach(), for(), and so on. Test them and see which one is actually the fastest way to loop an array with a lot of values in it. If you find the fastest one, then alwys use that to process loop and you can actually save a lot of time.
Usually people write same code such as loop over and over again in different places and they add up really fast, so you can end up spending a lot of time processing a stupid thing...
I hope this helps.
P.S. There are softwares to speed up the process such as Zend Optimizer. You should consider installing it, it really speeds up PHP.