PHP: How are array elements passed to the value comparison function when using usort ()?

I am trying to understand how the elements from my array are passed to my value comparison function when used usort(). Printing values $xand $ythe following for each iteration:

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 details:

$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;
    }
}

Array Sort:

usort( $data, 'value_compare_function' );

For the first iteration $x['k1']there is $data[1]['k1'], but $y['k1']- $data[0][k1]. Why are $datan't the elements from the array passed in value_compare_func()in order? For example, I expected $x['k1']to be $data[0]['k1']and $y['k1']for the $data[1]['k1']for the first iteration, but it was not.

+4
2

, , quicksort . , - ( , ), .

usort PHP, .

, , . . , , .

, , ( ), false , 0 integer. 0 , , .

1, $a > $b, -1, $a < $b 0, $a == $b .

+2

. , false == 0, .

:

function value_compare_func( $x, $y ) {
    if ( $x['k1'] > $y['k1'] ) {
        return 1;
     } elseif ( $x['k1'] < $y['k1'] ) {
         return -1;
     } else {
         return 0;
     }
 }

... .

0

Source: https://habr.com/ru/post/1616900/


All Articles