note 51873 deleted from function.array-multisort by cmb

From: Date: Sun, 29 Sep 2019 07:46:54 +0000
Subject: note 51873 deleted from function.array-multisort by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-212419@lists.php.net to get a copy of this message
Note Submitter: stevec at NO-/ dot /-SPAM dot qiguang dot net ---- 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.

« previous php.notes (#212419) next »