Skip to content
Advertisement

Accessing php variable from within function scope

I have this code in a codeigniter controller that’s the beginnings of a pagination/sorting feature for a table in the view. I’m passing order_by as a query parameter and then this is part of the controller action:

if ($order_by)
{
  function compare_items ($a, $b){
    return $b['value'][$order_by] <=> $a['value'][$order_by];
  };
  usort($data['items'], 'compare_items');
}

The problem is…I keep getting the error Undefined variable: order_by.

Since I’m checking that $order_by exists in the if statement, why am I getting this error? Even putting var_dump() inside the if statement returns a string that matches whatever I put in the query param. And hardcoding a value (return $b['value']['<test_param>'] <=> $a['value']['<test_param>'];) works just fine, even when if leave the if statement as is.

Is there some php scope behavior I’m not aware of that’s causing this error? I’m really a javascript/React dev, and I’m hoping I’m just missing something simple in php.

Advertisement

Answer

You must use “use” for external variables

if ($order_by)
{
    usort($data['items'], function ($a, $b) use ($order_by) {
        return $b['value'][$order_by] <=> $a['value'][$order_by];
    });
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement