Please enable Javascript to view this site.
 
 
  • Coding

  • Technology

  • Japanese

  • Chinese

  • Miscellaneous

PHP Bug in array_multisort()

April 13, 2005 | Tags: | Leave a comment

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:

$test1 = array(3,2,1);
$test2 = $test1;
$test3 = array('a', 'b', 'c');
array_multisort($test2, SORT_ASC, $test3);
echo 'test1:' . print_r($test1, true);
echo 'test2:' . print_r($test2, true);
echo 'test3:' . print_r($test3, true);

You would expect:

test1:Array
(
	[0] => 3
	[1] => 2
	[2] => 1
)
test2:Array
(
	[0] => 1
	[1] => 2
	[2] => 3
)
test3:Array
(
	[0] => c
	[1] => b
	[2] => a
)

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

test1:Array
(
	[0] => 1
	[1] => 2
	[2] => 3
)
test2:Array
(
	[0] => 1
	[1] => 2
	[2] => 3
)
test3:Array
(
	[0] => c
	[1] => b
	[2] => a
)

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:

$test1 = array(3,2,1);
$test2 = $test1;
$test3 = array('a', 'b', 'c');
$test2[0] = $test2[0];				// fix
array_multisort($test2, SORT_ASC, $test3);
echo 'test1:' . print_r($test1, true);
echo 'test2:' . print_r($test2, true);
echo 'test3:' . print_r($test3, true);

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.

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.