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

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.

Leave a Comment