I need to refactor a piece of php code to work with 7.2 but i am not sure if the way i did it is correct. I could use some info about it. This is the old code
JavaScript
x
private function sortByFields($field, &$array)
{
usort($array, create_function('$a, $b', '
$a = $a["' . $field . '"];
$b = $b["' . $field . '"];
if ($a == $b) return 0;
return ($a < $b) ? -1 : 1;
'));
return true;
}
And this is the code i refactored for 7.2
JavaScript
private function sortByFields($field, &$array)
{
usort($array, function ($a,$b) {
$a = $a["' . $field . '"];
$b = $b["' . $field . '"];
if ($a == $b) return 0;
return ($a < $b) ? -1 : 1;
});
return true;
}
Is it correct or did i mess up ?
Advertisement
Answer
You missed out on the “use” part so the function body does not know about the $field and messed up the $field array keys – see below:
JavaScript
private function sortByFields($field, &$array)
{
usort($array, function ($a,$b) use ($field) {
$a = $a[$field];
$b = $b[$field];
if ($a == $b) return 0;
return ($a < $b) ? -1 : 1;
});
return true;
}