phparrayssortingarray-multisort

Using array_multisort to sort integer ascending and sort corresponding string accordingly (php)


Using array_multisort, how can I sort prices from lowest to highest and then use that sorting order to sort its corresponding title?

Arrays

$pricearray = array(4.00, 56.99, 3.19);
$headerarray = array('four', 'fifty-six', 'three');

Desired Output

$pricearray = array(3.19, 4.00, 56.99);
$headerarray = array('three', 'four', 'fifty-six');

My Attempt

array_multisort($headerarray, $pricearray, SORT_ASC);

Solution

  • Sort $pricearray ascending (the default) and array_multisort will sort $headerarray with it:

    array_multisort($pricearray, $headerarray);
    

    To specify the order use it as the argument after the array:

    array_multisort($pricearray, SORT_ASC, $headerarray);
    

    See the manual where it states that some arguments can be swapped or omitted:

    array1_sort_order The order used to sort the previous array argument. Either SORT_ASC to sort ascendingly or SORT_DESC to sort descendingly.

    This argument can be swapped with array1_sort_flags or omitted entirely, in which case SORT_ASC is assumed.

    array1_sort_flags Sort options for the previous array argument:

    This argument can be swapped with array1_sort_order or omitted entirely, in which case SORT_REGULAR is assumed.