Andreas B
Andreas B

Reputation: 107

laravel - access variable outside loop

my code:

$atts->each(function($row){
  if($row->key == 30){
    $flag = $row->value;
    echo $flag;
  }
});

The value of $flag will be printed to the site. However, when I try to use the variable $flag outside the loop the variable is unknown.

Can someone tell me what I am missing or what has to be done to have access to that variable?

Thanks in advance!

Regards,

Andreas

Upvotes: 0

Views: 821

Answers (1)

Devon Bessemer
Devon Bessemer

Reputation: 35347

You would need to define that variable in the current scope and import that variable into your callback's scope with use.

$flag = null;
//Access flag by reference
$atts->each(function($row) use (&$flag) {
   ...
});

Since we're using Laravel Collections, I suggest you not use each() for this.

if ($row = $atts->where('key', 30)->first()) {
   $flag = $row->value;
}

This assumes there is only one row with a key of 30 though.

Upvotes: 3

Related Questions