PHP bug in array_multisort()

Posted Wednesday, April 13, 2005 at 11h54 in Computers

This is a php bug post, so if you don't use php, stop reading now.

Be careful when using array_multisort() on copies of arrays, as you might end up changing the original array. I lost half a day to debugging as a result of this. Given the following code:

  1. $test1 = array(3,2,1);
  2. $test2 = $test1;
  3. $test3 = array('a', 'b', 'c');
  4.  
  5. array_multisort($test2, SORT_ASC, $test3);
  6.  
  7. echo 'test1:';
  8. print_r($test1);
  9. echo 'test2:';
  10. print_r($test2);
  11. echo 'test3:';
  12. print_r($test3);

You would expect:

  1. test1:Array
  2. (
  3.     [0] => 3
  4.     [1] => 2
  5.     [2] => 1
  6. )
  7. test2:Array
  8. (
  9.     [0] => 1
  10.     [1] => 2
  11.     [2] => 3
  12. )
  13. test3:Array
  14. (
  15.     [0] => c
  16.     [1] => b
  17.     [2] => a
  18. )

However, if you run the code, you actually get:

  1. test1:Array
  2. (
  3.     [0] => 1
  4.     [1] => 2
  5.     [2] => 3
  6. )
  7. test2:Array
  8. (
  9.     [0] => 1
  10.     [1] => 2
  11.     [2] => 3
  12. )
  13. test3:Array
  14. (
  15.     [0] => c
  16.     [1] => b
  17.     [2] => a
  18. )

Note that the original ($test1) ends up being sorted even though it was never called by array_multisort(). To work around this, insert a statement to modify the copy ($test2) before calling array_multisort() on it. The following code will produce the expected "correct" results:

  1. $test1 = array(3,2,1);
  2. $test2 = $test1;
  3. $test3 = array('a', 'b', 'c');
  4.  
  5. $test2[0] = $test2[0];                // fix
  6. array_multisort($test2, SORT_ASC, $test3);
  7.    
  8. echo 'test1:';
  9. print_r($test1);
  10. echo 'test2:';
  11. print_r($test2);
  12. echo 'test3:';
  13. print_r($test3);

This seems to be a resurrection of the closed bug #8130. Also, someone reported this behavior in bug #32031, but it was incorrectly labeled "bogus" in reference to bug #25359, which is a different issue. This was tested on PHP 5.0.4-dev.