Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array_multisort unexpected influence

I did some tasks using the array_multisort function. During the writing of the script I did a var_dump, and got different results of $mainArray depending on the PHP version. 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);

Output 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 Output for 4.3.0 - 4.3.9, 5.0.0 - 5.0.5 I get 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 have influence on $mainArray but:

I really do not understand why in the second variant it was sorted, and in the first one is not. And, should I always check the script in different php versions?

Here you can check the script

like image 229
sergio Avatar asked Jan 09 '14 07:01

sergio


1 Answers

Your problem seems to be the different handling in the internals of foreach in the 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 may notice, we've included the ampersands & to the foreach loop's values, as they are necessary in PHP5+ in foreach loops to address that we want to reference the value so we can edit it directly. This will generate errors in older PHP versions though.

Also, clearly noted in the PHP.net docs:

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

like image 67
Ambidex Avatar answered Oct 05 '22 10:10

Ambidex