XF 2.2 Optimization foreach code

OkanOzturk

Active member
I been working on some addons and looking for optimization some foreach any suggest about this code?

Want to same users stories to same array.


PHP:
        $addedStoryUsers = [];

        $storyUsers = [];
        $var_limit = 1;
        foreach($stories AS $story){
            if(in_array($story->User->user_id, $addedStoryUsers))continue;
            if($var_limit <= $limit){
                $storyUsers[$story->User->user_id] = [
                    'user' => $story->User,
                    'stories' => []
                ];
                array_push($addedStoryUsers, $story->User->user_id);
                $var_limit++;
            }
        }
        foreach($stories AS $story){
            if(in_array($story->User->user_id, $addedStoryUsers)){
                array_push($storyUsers[$story->User->user_id]['stories'], $story);
            }
        }
        unset($addedStoryUsers);
        unset($var_limit);
 
You can get rid of the second foreach loop all together and just do that in the first one rather than "continue"'ing it.

Edit: Or more better

PHP:
 $addedStoryUsers = [];

        $storyUsers = [];
        $var_limit = 1;
        foreach($stories AS $story){
            if($var_limit <= $limit){
                $storyUsers[$story->User->user_id] = [
                    'user' => $story->User,
                    'stories' => []
                ];
                array_push($addedStoryUsers, $story->User->user_id);
             
            }
            $var_limit++;
            if(in_array($story->User->user_id, $addedStoryUsers)){
                array_push($storyUsers[$story->User->user_id]['stories'], $story);
            }
        }
        unset($addedStoryUsers);
        unset($var_limit);

Should still accomplish the same thing
 
Last edited:
Back
Top Bottom