Search code examples
phparrayslaravelphp-7.4

Why cant i change my array value? But if i add address pointer to array, it works


I have a code block to return as a json as follow;

    $data = $this->regionRepository->getDistrictsByGivenTravelTag();//returns an array

    foreach ($data as $city){
        $city["is_fav"] = false;
        if(auth()->user()){
            /** city */
            $fav_cities = auth()->user()->favoriteCities->pluck("id");

            if(in_array($city["city_id"],$fav_cities->toArray())){
                $city["is_fav"] = true;
            }
        }
    }

    dd($data);

This code block shows it without "is_fave". But I want to add "is_fav" key. Therefore, I added address pointer to my array inside the foreach as follow;

foreach ($data as &$city){
    ...
}
dd($data);

And now it works, so "is_fav" key has been added.

Could you explain why it's necessary?


Solution

  • Because in this scenario the foreach splits it and creates a new variable. So that $city doesn't affect the value of the array. You can use this alternative way;

    foreach ($data as $key=>$city){
      $data[$key]["is_fav"] = false;
      if(auth()->user()){
          /** city */
          $fav_cities = auth()->user()->favoriteCities->pluck("id");
    
          if(in_array( $data[$key]["city_id"],$fav_cities->toArray())){
             $data[$key]["is_fav"] = true;
          }
      }
    }