I'm trying to understand how the items from my array are passed to my value compare function when using usort(). A printout of the values of $x and $y for each iteration follows:
Iteration 1:
// $x
array(2) { ["k1"]=> int(21) ["k2"]=> string(1) "e" }
// $y
array(2) { ["k1"]=> int(920) ["k2"]=> string(1) "z" }
Iteration 2:
// $x
array(2) { ["k1"]=> int(842) ["k2"]=> string(1) "t" }
// $y
array(2) { ["k1"]=> int(21) ["k2"]=> string(1) "e" }
Iteration 3:
// $x
array(2) { ["k1"]=> int(920) ["k2"]=> string(1) "z" }
// $y
array(2) { ["k1"]=> int(21) ["k2"]=> string(1) "e" }
Iteration 4:
// $x
array(2) { ["k1"]=> int(842) ["k2"]=> string(1) "t" }
// $y
array(2) { ["k1"]=> int(920) ["k2"]=> string(1) "z" }
My data:
$data = array(
array( 'k1' => 920, 'k2' => 'z' ),
array( 'k1' => 21, 'k2' => 'e' ),
array( 'k1' => 842, 'k2' => 't' )
);
My custom function:
function value_compare_func( $x, $y ) {
if ( $x['k1'] > $y['k1'] ) {
return true;
} elseif ( $x['k1'] < $y['k1'] ) {
return false;
} else {
return 0;
}
}
Sort the array:
usort( $data, 'value_compare_function' );
For the first iteration, $x['k1'] is $data[1]['k1'] and $y['k1'] is $data[0][k1]. Why aren't the items from my $data array passed to value_compare_func() in order? For example, I would have expected $x['k1'] to be $data[0]['k1'] and $y['k1'] to be $data[1]['k1'] for the first iteration, but this isn't the case.
intvalues (1,-1and0) but usingfalsein place of-1andtruein place of1results in a sorted array with the exact same sequence of values.