I have such an array.

Array( array( 'name' => 'title 1', 'price' => 200 'id' => '737362' ) array( 'name' => 'title 2', 'price' => 100 'id' => '737363' )) 

Needed to sort by price. Here in the next topic I looked at the code:

 usort($array, function($a, $b){ return ($a['price'] - $b['price']);}); 

The code works fine, no problem. But I can not understand how it works. Explain what's going on? Why do we deduct?

  • To do this, you should not look into the next topic, but look at the manual of the programming language and read the description of the usort function ... in general, learning the basics of the language and basic methods of working with arrays / lines / files is a good lesson;) - Alexey Shimansky

1 answer 1

Why do we deduct?

Very good question.

We subtract it because the function usort works this way : the function we pass as an argument must return a positive number if the first argument is greater than the second; negative - if less; and zero if the arguments are equal. This, in fact, allows the function to understand in which order to rank the elements of the array.

Well, the easiest way to get this result is to subtract the first operand from another!

It’s harder to get strings - you have to use the strcmp () function to sort them, which also returns 1, -1 and 0 in the described cases.