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

vipin93's avatar
Level 13

How to limit value within foreach loop?

I try to make marksheet of students so there are four marks with subject id 1 so when i try to make print in foreach each loop its printing four times like

@foreach($exammarks as $exammark)

                          <tr>                 
                          <td rowspan="">{{$exammark->subjects['name'] }}</td>                  
                            <td rowspan="">{{$exammark->examnames['name'] }}</td>
                            <td>25</td>
                            <td>33</td>
                          </tr>
@endforeach 

my query

$exammarks = ExamMark::whereHas('courses',function($q) use($course, $cdate){
                          $q->where('id',$course)
                            ->where('created_at',$cdate);
                     })->orderBy('subject_id')
                     ->where('student_id',Auth::id())
                     ->with('courses','sections','examnames','subjects')
                     ->get();

here output https://www.dropbox.com/s/k4mb8u8h3kdxo5v/2.PNG?dl=0

now here subjects repeating two times but i want to limit only one

0 likes
9 replies
jlrdw's avatar

Have you tried to use a nested foreach?

Baryla's avatar

Have you tried grouping the results by id?

->groupBy('subject_id')
1 like
BelalMostafa's avatar

what about setting a boolean to true before the foreach and set it to true inside the foreach, and echo only if it is true

so I think you can say something like

                $limit = true;
               @foreach($exammarks as $exammark)
                  if($limit){
                         echo "something"
                     }
                  $limit  = false;
                      <tr>                 
                      <td rowspan="">{{$exammark->subjects['name'] }}</td>                  
                        <td rowspan="">{{$exammark->examnames['name'] }}        
                       </td>
                        <td>25</td>
                        <td>33</td>
                      </tr>
                @endforeach 

I hope that I understood you well

vipin93's avatar
Level 13

@Baryla when i tried to group by its giving errors, i have selecteraw

akgarg007's avatar

$i = 0; foreach ($arrays as $array) { // you code if (++$i == 10) break; }

Please or to participate in this conversation.