Incorrect PHP effect array_multisort

I completed some tasks using the array_multisort function. While writing the script, I did var_dump and got different $mainArray results depending on the version of PHP. Here is the code:

 $mainArray = array( 0 =>array( "key1" => array(7,4,5), 'key2' => array('cc','aa') ) ); foreach($mainArray as $secondArray){ foreach($secondArray as $array){ array_multisort($array); } } var_dump($mainArray); 

Conclusion for 4.3.10 - 4.4.9, 5.1.1 - 5.5.7 :

 array(1) { [0]=> array(2) { ["key1"]=> array(3) { [0]=> int(7) [1]=> int(4) [2]=> int(5) } ["key2"]=> array(2) { [0]=> string(2) "cc" [1]=> string(2) "aa" } } } 

But the output for 4.3.0 - 4.3.9, 5.0.0 - 5.0.5 I get a sorted array:

 array(1) { [0]=> array(2) { ["key1"]=> array(3) { [0]=> int(4) [1]=> int(5) [2]=> int(7) } ["key2"]=> array(2) { [0]=> string(2) "aa" [1]=> string(2) "cc" } } } 

I knew that array_multisort($array) would not affect $mainArray , but:

I really don’t understand why in the second variant it was sorted, but in the first - no. And, should I always check the script in different versions of PHP?

Here you can check the script

+6
source share
2 answers

It seems that your problem is related to different processing in internal foreach files in different versions of PHP. Try the following.

 <?php $mainArray = array( 0 =>array( "key1" => array(7,4,5), 'key2' => array('cc','aa') ) ); foreach($mainArray as &$secondArray){ foreach($secondArray as &$array){ array_multisort($array); } } var_dump($mainArray); ?> 

As you can see, we included ampersands & in the values ​​of the foreach loop, since they are needed in PHP5 + in the foreach loops, so that we want to refer to the value so that we can edit it directly. However, this will lead to errors in older versions of PHP.

In addition, PHP.net docs clearly states:

To be able to directly modify array elements in a loop, $ value is preceded with &. In this case, a value will be assigned to the link.

+3
source

I think what happens is that you get (in the first version of the code) a copy of the array. This is normal behavior for a PHP script. Then you sort the copy, and the original array remains unchanged. If you want to sort the original array, you must do:

 foreach($mainArray as &$secondArray){ foreach($secondArray as &$array){ array_multisort($array); } } 

Which gets internal arrays by reference.

EDIT

If you need a version that will always work, you just need to replace the elements of the original array.

 <?php $mainArray = array( 0 =>array( "key1" => array(7,4,5), 'key2' => array('cc','aa') ) ); foreach($mainArray as $secondIndex=>$secondArray){ foreach($secondArray as $index=>$array){ array_multisort($array); $secondArray[$index] = $array; } $mainArray[$secondIndex] = $secondArray; } var_dump($mainArray); 

Check it out at http://3v4l.org/Bk1YM

0
source

All Articles