Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

belankus's avatar

Get Variable type Array From Nested IF in foreach Loop

Hi all, this is my first post on the forum, and it would be great if anyone can solfe my problem

I am building comment section, and i need to loop each comment from database using this logic

Point 1 : if comment has parent_id 0, then run html block with padding-left-0 (no indent)

Point 2: if comment has same parent_id with id in Point 1, then run blocks right after Point 1 with indented html block

Point 3: if comment has same parent_id with id in Point 2, then run block, with same level indentation with point 2

So it will be only 2 level of indentation :
Level 1 : Point 1 (original reply)
Level 2: Point 2 and so on (reply of original reply)
This loop wll sort by date ASC

My idea is here

1. I make looping through entire comments to get parent_id = 0 (Level 1)
2. I make looping inside each of Level 1 to get Level 2
3. The Problem
 - I want to make comment Level 2, that is related to Point 2 (not directly with Level 1)
 - Different behaviour with Point 1 and 2, i dont want nested loop each reply, but sorted by date
 - Let's say :
    A has commented on Post X (Level 1)
    B reply A's comment (Level 2)
    C reply B's comment (Level 2)

I have tried with this structure

@foreach ($comments as $comment)
    @if ($comment->parent_id == 0)
        <article>
            {{-- Level 1 --}}
        </article>
        @foreach ($comments as $c)
            @if ($c->parent_id == $comment->id)
                <article>
                    {{-- Level 2 --}}
                </article>

                @foreach ($comments as $key => $r)
                    @if ($r->parent_id == $c->id)
                        @php
                            $temp[$key] = $r;
                        @endphp
                    @endif
                @endforeach
            @endif
        @endforeach
        {{-- I want to call variable $temp here and loop For other Level 2 --}}
    @endif
@endforeach

And im stuck in getting $temp variable from inside the loop. I dont want the block appear right inside the loop, so i am supposed to only place variable, and place the variable result to the place i want.

0 likes
1 reply
Mega_Aleksandar's avatar

Hi, Not an expert here, but I would try and build a nested array using a recursive function to build the comments tree first (before trying to output them), then, with that structure, I would do nested for loops. In that way, you will always have Level 1 in the "main" array, under it you will have Level 2 if the parent_id is the same as comment_id etc. That way it will be much easier to loop through. Just an idea, hope it helps.

Please or to participate in this conversation.