array_multisort and dynamic variable options

Im trying to sort any array with array_multisort and everything is working great. However, based on conditions in my script, I need to change the options. So What I have so far is this:

array_multisort(
 $sort1,SORT_ASC,
 $sort2,SORT_ASC,
 $sort3,SORT_ASC, 
 $arraytosort
);

and what I would like to have is something like this:

$dynamicSort = "$sort1,SORT_ASC,$sort2,SORT_ASC,$sort3,SORT_ASC,";

array_multisort(
 $dynamicSort, 
 $arraytosort
);

Any suggestions?


Solution 1:

You could try to use call_user_func_array. But I've never tried it on a built-in function before. Here is an example:

$dynamicSort = "$sort1,SORT_ASC,$sort2,SORT_ASC,$sort3,SORT_ASC";
$param = array_merge(explode(",", $dynamicSort), array($arrayToSort))
call_user_func_array('array_multisort', $param)

Solution 2:

I had the same problem with this answer: "Argument #1 is expected to be an array or a sort flag"

For anyone having the same problem try this instead:

$dynamicSort = array(&$sort1, SORT_ASC, &$sort2, SORT_ASC, &$sort3, SORT_ASC); 
$param = array_merge($dynamicSort, array(&$arrayToSort));
call_user_func_array('array_multisort', $param);

Note that i have used the reference to my variables "&$" instead of $. This works great in php 5.3 but may cause error in 5.2 due to a bug.