Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

usort

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.

like image 764
Michael Avatar asked Jul 13 '10 08:07

Michael


2 Answers

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.

like image 148
Achronos Avatar answered Sep 18 '22 08:09

Achronos


To resolve this issue we can handle as below

1) use error_reporting

$a = array('id' => 2,'val' => 3, 'ind' => 3); $errorReporting = error_reporting(0); usort($a); error_reporting($errorReporting); 

2) use @usort($a);

$a = array('id' => 2,'val' => 3, 'ind' => 3); @usort($a); 
like image 39
panditharshad Avatar answered Sep 21 '22 08:09

panditharshad