Having said all that...
How can we tell where the problem is when you show us only that function?
There is nothing wrong in the function code, per se, but there could well be problems in the way it is called.
You need to show us a lot more code. Or, better, give us a live URL to look at.
By the by, you need to end your code section with [/code], not just [code], if you want us to see your code in proper indentation, etc.
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.