usort(): Array was modified by the user comparison function

Michael picture Michael · Jul 13, 2010 · Viewed 22.4k times · Source

I have a web application that runs fine on our Linux servers but when running on Mac OS with the Zend Community Edition Server using PHP 5.3 we get the error:

usort(): Array was modified by the user comparison function

every time a page loads for the first time (it takes about 2 minutes for a page to tick over and load, on the linux servers the page loads in 1 second).

Has anyone else experienced this or has any idea how I can fix the problem, I have tried playing around with PHP and Apache memory settings with no luck.

Answer

Achronos picture Achronos · Jun 11, 2012

There is a PHP bug that can cause this warning, even if you don't change the array.

Short version, if any PHP debug functions examine the sort array, they will change the reference count and trick usort() into thinking you've changed the data.

So you will get that warning by doing any of the following in your sort function (or any code called from it):

  • calling var_dump or print_r on any of the sort data
  • calling debug_backtrace()
  • throwing an exception -- any exception -- or even just creating an exception

The bug affects all PHP 5 versions >= 5.2.11 but does not affect PHP >= 7. See the bug report for further details.

As far as I can see, the only workaround is either "don't do that" (which is kind of hard for exceptions), or use the error suppression operator @usort() to ignore all errors.