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?
Don't use
create_function
in this instance. You can also write it like this:You need to escape your variable names. Per the
create_function
documentation (emphasis mine):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.