I’ve been fighting with this PHP-snippet for some hours and I can’t figure it out…
How does PHP determines the order when to pass the variables in this snippet:
function myfunction ($left, $right) {
echo $left;
echo '<br>';
echo $right;
}
$a = array ('one', 'two', 'three', 'four');
usort($a, 'myfunction');
In this case, the variables are passed like this:
$left = 'two' - $right = 'one';
$left = 'four' - $right = 'two';
$left = 'three' - $right = 'two';
$left = 'four' - $right = 'three';
But how is this sequence determined?!? I’ve been cracking my head and couldn’t find any logic…
usortuses the quicksort algorithm. You’ll see that if you change your function to return one of the expected values (-1, 0, 1), the results will be different:From the article: