PHP create_function with nested arrays

I need to use create_functionit because the server the application is running on has an outdated version of PHP.

The problem is that the elements that I pass in usortare arrays, and I need to sort by value inside the array:

$sort_dist = create_function( '$a, $b', "
    if( $a['order-dir'] == 'asc' ) {
        return $a['distance'] > $b['distance'];
    }
    else {
        return $a['distance'] < $b['distance'];
    }" 
);

usort( $items, $sort_dist );

Gives an error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING

Removing links to ['distance']and ['order-dir']resolves this error.

Does anyone know how to use create_functionwith nested arrays?

0
source share
2 answers

Do not use create_functionin this case. You can also write it like this:

function sort_by_distance($a, $b) {
    if( $a['order-dir'] == 'asc' ) {
        return $a['distance'] > $b['distance'];
    }
    else {
        return $a['distance'] < $b['distance'];
    }
}

usort( $items, "sort_by_distance" ); // pass the function name as a string
+1
source

You need to avoid variable names. According to the create_functiondocumentation (my selection):

. , , , , , . \$avar.

, , , , , create_function, .

+1

All Articles