Ramesh Khadka
Ramesh Khadka

Reputation: 3

how can i change the values of arrays dynamically in each loop?

I have my data in an array so I am trying to change the values of arrays dynamically. For Example I have $name[0] inside foreach loop.

I want it to be $name[1], $name[2], $name[3] automatically in each loop. I am using laravel framework.

<tr>
 <td>Sn</td>
 <td>Name</td>
 <td>post</td>
 <td>Address</td>
 <td>father</td>
 <td>Grandfather</td>
 <td>Ctz no</td>
 <td>Contact</td>
</tr>
<?php $i = 1 ?>
@foreach($officials as $official)
<tr>
 <td>$i++</td>
 <td>{{$name[0]}}</td>
 <td>{{$post[0]}}</td>
 <td>{{$address[0]}}</td>
 <td>{{$father[0]}}</td>
 <td>{{$grandfather[0]}}</td>
 <td>{{$ctz[0]}}</td>
 <td>{{$contact[0]}}</td>
</tr>
@endforeach

Upvotes: 0

Views: 66

Answers (2)

user8865860
user8865860

Reputation: 61

You could keep increment value of a variable while going through foreach

            <tr>
             <td>Sn</td>
             <td>Name</td>
             <td>post</td>
             <td>Address</td>
             <td>father</td>
             <td>Grandfather</td>
             <td>Ctz no</td>
             <td>Contact</td>
           </tr>
           @php 
            $i = 0;
           @endphp
           @foreach($officials as $official)
           <tr>
             <td>@php echo $i; @endphp</td>
             <td>@php echo $name[$i]; @endphp</td>
             <td>@php echo $post[$i]; @endphp</td>
             <td>@php echo $address[$i]; @endphp</td>
             <td>@php echo $father[$i]; @endphp</td>
             <td>@php echo $grandfather[$i]; @endphp</td>
             <td>@php echo $ctz[$i]; @endphp</td>
             <td>@php echo $contact[$i]; @endphp</td>
           </tr>
           @php
             $i++;
           @endphp
           @endforeach

this will work, but seems to be trivial, you could define a custom blade directive implementing your own rule in AppServiceProviders in Laravel. The official documentation is here.

Upvotes: 1

JIJOMON K.A
JIJOMON K.A

Reputation: 1280

please try this

@foreach($officials as $official)
               <tr>
                 <td>$loop->iteration</td>
                 <td>{{$official['name']}}</td>
                 <td>{{$official['post']}}</td>
                 <td>{{$official['address']}}</td>
                 <td>{{$official['father']}}</td>
                 <td>{{$official['grandfather']}}</td>
                 <td>{{$official['ctz']}}</td>
                 <td>{{$official['contact']}}</td>
               </tr>
               @endforeach

Upvotes: 0

Related Questions