How does this usort cmp function actually work?
Asked Answered
V

2

2

There's an answer here: Combine two array and order this new array by date

It explains how two arrays can be merged and then sorted by date.

function cmp($a, $b){
    $ad = strtotime($a['date']);
    $bd = strtotime($b['date']);
    return ($ad-$bd);
}
$arr = array_merge($array1, $array2);
usort($arr, 'cmp');

the solution looks quite elegant, but I'm confused by

return ($ad-$bd);

I mean there's no comparison operator, it just subtracts

function newFunc($a, $b) {
    return($a-$b);
}

echo newFunc(5,3);

returns 2

So how does this actually indicate how to sort the arrays?

Update:

I read further the documentation on the usort page as suggested. Does it perform this subtraction with each of the elements? Does it iterate through each array element and subtracts it from other elements? Just trying to wrap my head around this.

Vernettaverneuil answered 31/8, 2016 at 7:41 Comment(2)
Take a deeper look at usortCogitation
@Robert look again. I've added a more modern answer which implements the 3-way comparison operator ("spaceship operator") instead of subtracting string values.Seemaseeming
A
3

To quote the documentation, a usort's value_compare_func is a function that:

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

In this case, both dates are converted to a Unix timestamp, i.e., the number of seconds since the epoch. If $a comes before $b, it will have less seconds since the epoch, so subtracting it from $b will return a negative number. If it comes after $b, subtracting the two will return a positive number, and if they are the same, the subtraction will of course return zero.

Apiarian answered 31/8, 2016 at 7:46 Comment(1)
thank you for the reply it makes things more clear, I also read additional comments on the usort php page. What does $a and $b represent? And what does it do on the background? It checks each array element with the rest of the elements? Just trying to wrap my head around this.Vernettaverneuil
L
2

If you read a manual, you see:

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

By substracting values you get either positive or negative or 0 value, which allows to sort values.

Lori answered 31/8, 2016 at 7:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.