Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

paklic9's avatar

Undefined variable in function with query

Hi, I have problem with my function, error is: "Undefined variable: filtry". I know why, the variable $filtry have to be defined in query function (like variable $j is), then it is working. But I cannot have this variable static, because variable $filtry will be always diffrent, so I need set it before function, then call it in function. Is it possible?

Thanks in advance for help.

My function:

function dbselect($tabulka, $filtry){
  $inzerce = \DB::table($tabulka)
    ->where(function($query){
      $j = 0;
      foreach ($filtry as $filtr) {
      $filtr = \Request::has($filtr) ? \Request::get($filtr) : [];
        if(isset($filtr)){
          $i = 0;
          foreach ($filtr as $polozka) {
            if ($i == 0) {
              $query->where($filtry[$j],'=', $polozka);
              $i++;
            }
            else{
            $query->orwhere($filtry[$j],'=', $polozka);
            $i++;
            }
          }
        }
      $j++;
      }
    })->get();
}

Calling function:

$filtry = ['kategorie'];
dbselect('zviratas', $filtry);
0 likes
2 replies
topvillas's avatar
Level 46

Pass $filtry into the anonymous function with use .

$inzerce = \DB::table($tabulka)
->where(function($query) use($filtry) {
    ...
}
1 like
paklic9's avatar

oh, that's easy. I was trying to do it much harder. :D I am beginner. Thank you so much.

Please or to participate in this conversation.