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.

5
  • 1
    Pass it by reference and assign it back? foreach ($slideShow as &$slide) { $slide['image'] = str_replace('_xs', "", $slide['image']); } Commented Jul 24, 2020 at 8: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. :/ Commented Jul 24, 2020 at 8: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. Commented Jul 24, 2020 at 8:19
  • @Jeto Uh thanks for bringing it to my attention! It's working now! Commented Jul 24, 2020 at 8:22
  • @Qirel Thanks a lot for helping me out! It's working now Commented Jul 24, 2020 at 8:23

1 Answer 1

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']);
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.