1

Let's consider the following code:

$arr = [ [ 'expiryDate' => '2018.6' ], [ 'expiryDate' => '2018.5' ], [ 'expiryDate' => '2018.7' ] ];

$sortby = "expiryDate";

usort($arr, function($a1, $a2) use ($sortby) {      
    $d1 = DateTime::createFromFormat("Y.m", $a1[$sortby])->getTimestamp();
    $d2 = DateTime::createFromFormat("Y.m", $a2[$sortby])->getTimestamp();
    return $d1 - $d2;
});
echo "<pre>";
var_dump($arr);

The above code sorts the $arr according to expiryDate, no problem.

Now consider this:

$arr = [ [ 'expiryDate' => '2018.6' ], [ 'expiryDate' => '2018.5' ], [ 'expiryDate' => '2018.7' ] ];

function sortItOutYourself($arr, $sortby, $isDate) {    
    if( $isDate ) {
        usort($arr, function($a1, $a2) use ($sortby) {
            $d1 = DateTime::createFromFormat("Y.m", $a1[$sortby])->getTimestamp();
            $d2 = DateTime::createFromFormat("Y.m", $a2[$sortby])->getTimestamp();
            return $d1 - $d2;
        });
    }
}

sortItOutYourself($arr, "expiryDate", true);
echo "<pre>";
var_dump($arr);

Both the codes have same comparator but output is different. Basically the second code is failing to sort as required. What's wrong with the second snippet? What am I missing here?

  • 2
    Pass by reference... `function sortItOutYourself(&$arr, $sortby, $isDate) { ` – Mark Baker Feb 13 '18 at 08:03
  • Btw, in PHP, Arrays are always passed by value. But, if the array contains objects then each of the objects is passed by reference and the array is passed by value . Here is a explanation : https://stackoverflow.com/a/36372313/452213 – sudip Feb 13 '18 at 08:17

1 Answers1

2

The sort is working, but your function never passes the result back, so either return the array or change the function declaration to ...

function sortItOutYourself(&$arr, $sortby, $isDate) {

The & means it uses the same array rather than a copy.

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55