Wednesday, December 14, 2022

[FIXED] How to add a loop inside a variable php

Issue

I have to use a foreach loop inside a variable in php but Im not sure of the right syntax. This is what Ive tried but it shows an error(Parse error: syntax error, unexpected 'foreach' (T_FOREACH))

 $doctor = foreach($doctor->find_all() as $d){
      echo '<td>'.$d->getName().'</td>';
      echo '<td>'.$d->getEmail().'</td>';
      echo '<td>'.$d->getPhone().'</td>';
      echo '<td>'.$d->getGender().'</td>';
      echo '<td>'.$d->getSpecialist().'</td>';
      echo '<td><a href="../doctor/updatedoc.php"><i class="fa-solid fa-pen-to-square"></i></a></td>';
      echo  '<td><a href=""><i class="fa-solid fa-trash"></i></a></td>';
    };

Solution

You cannot assign loop on variable or with the echo instead you can direct save the data to variable inside the loop

$doctor = "";
foreach($doctor->find_all() as $d){
      $doctor .='<td>'.$d->getName().'</td>';
      $doctor .='<td>'.$d->getEmail().'</td>';
      $doctor .='<td>'.$d->getPhone().'</td>';
      $doctor .='<td>'.$d->getGender().'</td>';
      $doctor .='<td>'.$d->getSpecialist().'</td>';
      $doctor .='<td><a href="../doctor/updatedoc.php"><i class="fa-solid fa-pen-to-square"></i></a></td>';
      $doctor .='<td><a href=""><i class="fa-solid fa-trash"></i></a></td>';
    }; 


Answered By - Existed Mocha
Answer Checked By - Candace Johnson (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.