note 51873 added to function.array-multisort
| From: | stevec at NO-/ dot /-SPAM dot qiguang dot net | Date: | Wed, 13 Apr 2005 15:19:04 +0000 |
| Subject: | note 51873 added to function.array-multisort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-87955@lists.php.net to get a copy of this message | ||
Be careful when using array_multisort() on copies of arrays, as you might end up changing the
original array. Given the following code:
<?php
$test1 = array(4,3,2,1);
$test2 = $test1;
$test3 = array('a', 'b', 'c', 'd');
array_multisort($test2, SORT_ASC, $test3);
echo 'test1:';
print_r($test1);
echo 'test2:';
print_r($test2);
echo 'test3:';
print_r($test3);
?>
You would expect:
test1:Array
(
[0] => 4
[1] => 3
[2] => 2
[3] => 1
)
test2:Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
test3:Array
(
[0] => d
[1] => c
[2] => b
[3] => a
)
However, if you run the code, you actually get:
test1:Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
test2:Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
test3:Array
(
[0] => d
[1] => c
[2] => b
[3] => 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:
<?php
$test1 = array(4,3,2,1);
$test2 = $test1;
$test3 = array('a', 'b', 'c', 'd');
$test2[0] = $test2[0]; // fix
array_multisort($test2, SORT_ASC, $test3);
echo 'test1:';
print_r($test1);
echo 'test2:';
print_r($test2);
echo 'test3:';
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.
----
Manual Page -- http://www.php.net/manual/en/function.array-multisort.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+51873
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+51873&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+51873&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+51873&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+51873&report=yes&reason=useless
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+51873&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+51873&report=yes
Search -- http://master.php.net/manage/user-notes.php