PHP create_function with nested arrays

309 views Asked by At

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

The issue is that the items I pass into usort are arrays and I need to sort by a value within 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 the references to ['distance'] and ['order-dir'] removes this error.

Does anyone know how to use create_function with nested arrays?

2

There are 2 answers

1
Halcyon On

Don't use create_function in this instance. 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
Jimmy Sawczuk On

You need to escape your variable names. Per the create_function documentation (emphasis mine):

Usually these parameters will be passed as single quote delimited strings. The reason for using single quoted strings, is to protect the variable names from parsing, otherwise, if you use double quotes there will be a need to escape the variable names, e.g. \$avar.

I should note for future readers that Frits van Campen's answer is probably the solution you should use, but if you absolutely need to use create_function, my answer should work.