user1673473
user1673473

Reputation: 51

how to use variable outside foreach loop

How to return $value after loop with its returned data ? I think to create array before loop and equal it to $v to use it after loop but it didn't work.

Any idea on how to solve this problem ?

// create array
$v = array();

// start loop
foreach ($this->json_data->locations as $key => $value) {
    if ($value->country_name == $data['city']->country_name)
        // return $value with data
        return $v = $value ; 
}

echo $v->country_name

Upvotes: 0

Views: 9224

Answers (4)

DS9
DS9

Reputation: 3033

try this:

$v = array(); 
foreach ($this->json_data->locations as $key => $value) {
 if ($value->country_name == $data['city']->country_name)
 {
    if(!in_array($value,$v))
    {
     array_push($v,$value);                 
    }
 }
}

Upvotes: 4

kondapaka
kondapaka

Reputation: 132

I think the following code will helps you.

// create array
     $v = array();
// start loop
        foreach ($this->json_data->locations as $key => $value) {
            if ($value->country_name == $data['city']->country_name)
// return $value with data                  
           array_push($v, $value); 
        }
             return $v;

Upvotes: 0

Shoogle
Shoogle

Reputation: 206

If like using 'return' try this.

$v = iLikeUsingReturn($this,$data);

function iLikeUsingReturn($t,$d){
  foreach ($t->json_data->locations as $key => $value) {
                if ($value->country_name == $d['city']->country_name)
                    return $value ; 
  }
  return array();
}

Upvotes: 0

Puppuli
Puppuli

Reputation: 464

try this

 $v = array();
    $i=0;
    // start loop
                foreach ($this->json_data->locations as $key => $value) {
                    if ($value->country_name == $data['city']->country_name)
    // return $value with data
                         $i++;
                         $v[$i] = $value ; 
                }
    //print $v
                print_r($v)

Upvotes: 2

Related Questions