PHP usort with missing values

855 views Asked by At

How can I manipulate the usort function here to move objects missing a LastUse key to the bottom?

Short of have another loop prior to this that sets LastUse as a 0 value, I'm not entirely sure the best way to achieve it.

I'd be looking to the sorted LastUse values at the top of the list, and those that do not have a value at the bottom of the list.

    usort($trackdata, function ($a, $b) {
        return strtotime($b->LastUse) - strtotime($a->LastUse);
    });
1

There are 1 answers

6
MilanG On BEST ANSWER

Should be something like this:

   usort($trackdata, function ($a, $b) {
        if (empty($a->LastUse) && empty($b->LastUse)) return 0;
        if (empty($a->LastUse)) return -1;
        if (empty($b->LastUse)) return 1;
        return strtotime($b->LastUse) - strtotime($a->LastUse);
    });

Didn't test it so if they swimp up to the top move minus sign from first row to second to change their position.