php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #12936 array_multisort and passing by reference
Submitted: 2001-08-23 22:17 UTC Modified: 2001-08-31 11:10 UTC
From: kat at audiogalaxy dot com Assigned:
Status: Closed Package: Arrays related
PHP Version: 4.0.4 OS: linux
Private report: No CVE-ID: None
 [2001-08-23 22:17 UTC] kat at audiogalaxy dot com
When called inside a function array_multisort changes the global variables instead of the local copy the function should be working with.

<?php

$sortKeys = array(3, 2, 4, 1, 5);
$a = array(111 => '111', 222 => '222', 333 => '333', 444 => '444',
           555 => '555');

echo "initial arrays:<br>";
echo "sortKeys: "; var_dump($sortKeys); echo "<br>";
echo "a: "; var_dump($a); echo "<br>";

echo "<br>";

msortWithRef($sortKeys, $a);

echo "after msortWithRef:<br>";
echo "sortKeys: "; var_dump($sortKeys); echo "<br>";  
echo "a: "; var_dump($a); echo "<br>";  

echo "<br>";

msortWithoutRef($sortKeys, $a);    

echo "after msortWithoutRef:<br>";
echo "sortKeys: "; var_dump($sortKeys); echo "<br>";
echo "a: "; var_dump($a); echo "<br>";

function msortWithoutRef($array1, $array2)
{
    array_multisort($array1, $array2);
}

function msortWithRef($array1, $array2)
{
    array_multisort(&$array1, &$array2);
}

?>

output:

initial arrays:
sortKeys: array(5) { [0]=> int(3) [1]=> int(2) [2]=> int(4) [3]=> int(1) [4]=> int(5) } 
a: array(5) { [111]=> string(3) "111" [222]=> string(3) "222" [333]=> string(3) "333" [444]=> string(3) "444" [555]=> string(3) "555" } 

after msortWithRef:
sortKeys: array(5) { [0]=> int(3) [1]=> int(2) [2]=> int(4) [3]=> int(1) [4]=> int(5) } 
a: array(5) { [111]=> string(3) "111" [222]=> string(3) "222" [333]=> string(3) "333" [444]=> string(3) "444" [555]=> string(3) "555" } 

after msortWithoutRef:
sortKeys: array(5) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) [4]=> int(5) } 
a: array(5) { [0]=> string(3) "444" [1]=> string(3) "222" [2]=> string(3) "111" [3]=> string(3) "333" [4]=> string(3) "555" } 

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2001-08-31 11:10 UTC] andrei@php.net
It's a side-effect of the implementation. It could be fixed if I forced all arguments to be passed by reference, but that means that you can't specify SORT_* constants directly as arguments..
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Tue Mar 19 11:01:28 2024 UTC