0

I have written this code with Yii2 a long time ago to fetch photos for a slideshow and then choose another image size among several images and although it works, as I haven't been working with PHP recently, I don't understand why. I think I should be able to use a simple foreach loop, but when I change it to a simple one, it doesn't work. This is the code:

public static function getSlideShowPage($type)
{
    $slideShow=SlideShow::find()
        ->select(['title','image','title_position','subtitle', 'title_color'])
        ->where(['deleted' => 0,'active'=>1,'type'=>$type])
        ->orderBy('id ASC')
        ->groupBy('id')
        ->asArray()
        ->all();
    if(!empty($slideShow))
    foreach ($slideShow as $key=>$slide){
        $slideShow[$key]['image']=str_replace('_xs', "", $slide['image']);
    }
    return $slideShow;
}

and what I'm having a problem with is this part:

    if(!empty($slideShow))
    foreach ($slideShow as $key=>$slide){
        $slideShow[$key]['image']=str_replace('_xs', "", $slide['image']);
    }
   

Why can't I write it like this:

if(!empty($slideShow))
    foreach ($slideShow as $slide){
        str_replace('_xs', "", $slide['image']);
    }

In each foreach loop, I choose one of the array elements and replace the URL of the image. I would appreciate any help or suggestion.

Wiz
  • 43
  • 1
  • 5
  • 1
    Pass it by reference and assign it back? `foreach ($slideShow as &$slide) { $slide['image'] = str_replace('_xs', "", $slide['image']); }` – Qirel Jul 24 '20 at 08:11
  • @Qirel I did that too, it wont work. In my opinion they are doing the same thing, so I cant figure out why that works and this doesn't. :/ – Wiz Jul 24 '20 at 08:16
  • 1
    @Wiz Are you sure you didn't forget `&`? That code is basic pass-by-reference and does work, so you must be missing something. – Jeto Jul 24 '20 at 08:19
  • @Jeto Uh thanks for bringing it to my attention! It's working now! – Wiz Jul 24 '20 at 08:22
  • @Qirel Thanks a lot for helping me out! It's working now – Wiz Jul 24 '20 at 08:23

1 Answers1

2

As @Qirel mentioned you should pass it as reference but also you have to do something with the result of str_replace:

foreach ($slideShow as &$slide){
    $slide['image'] = str_replace('_xs', '', $slide['image']);
}
Bizley
  • 17,392
  • 5
  • 49
  • 59
  • 1
    If you're doing this though, you should also do `unset($slide)` after the loop for safety, or you're gonna have a bad surprise if you happen to make use of `$slide` later in the script. – Jeto Jul 24 '20 at 08:22