In php, when we want to sort a array
in a custom way we can use the function usort
.
I know that for this function to work, we should use values 1
, 0
and -1
.
In case, if I wanted to sort this array
down in descending order, we could do this:
$array[0]['preco'] = 10.00;
$array[1]['preco'] = 25.00;
$array[2]['preco'] = 20.00;
usort($array, function ($a, $b)
{
return $b['preco'] > $a['preco'] ? 1 : 0;
});
The result would be:
[
[
"preco" => 25.0,
],
[
"preco" => 20.0,
],
[
"preco" => 10.0,
],
]
]
If you reverse the variables in the comparison, the result would be different:
usort($array, function ($a, $b) {
$a['preco'] > $b['preco'] ? 1 : 0;
});
The result would be:
[
[
"preco" => 10.0,
],
[
"preco" => 20.0,
],
[
"preco" => 25.0,
],
]
I also reduce the comparison by simply doing a subtraction operation, when I want to reverse sort:
usort($array, function ($a, $b)
{
return $b['preco'] - $a['preco'];
});
I know that if we used the value 0
for all comparisons, the results would remain in the same position.
I know how to change the ordering of values, but I do not understand how php does it internally.
And it is possible to do this operation in Python
as well.
Example:
lista = [1, 2, 3]
lista.sort(lambda a,b: b-a)
#[3, 2, 1]
How is this comparison made, so that the languages knew which is the first and which is the second?
What does 1
or -1
internally represent for these sorting functions?