Mohammad Mirdar
Mohammad Mirdar

Reputation: 56

undefined variable error in foreach loop

I have a problem where I use this foreach code. I receive an undefined variable: task error.

<?
  $data = file_get_contents('data.json');
  $array = json_decode($data, 1);
  foreach ($array as $task) { ?>
    <tr>
      <td>
        <?= $task['name'] ?>
      </td>
      <td>Data</td>
      <td>Data</td>
      <td>Data</td>
      <td><button class="btn btn-primary"><?= icon('stop'); ?></button></td>
      <td><button class="btn btn-danger"><?= icon('times'); ?></button></td>
    </tr>
  <? } 
?>

Upvotes: 0

Views: 1098

Answers (1)

Asfandyar Khan
Asfandyar Khan

Reputation: 1738

You forget to add the start of php file <?php and at the end <?php } ?>, which will result in different errors

<?php
$data = file_get_contents('data.json');
$array = json_decode($data , 1);
foreach ($array as $task) { ?>
    <tr>
        <td>
            <?= $task['name']; ?>
        </td>
        <td>Data</td>
        <td>Data</td>
        <td>Data</td>
        <td><button class="btn btn-primary"><?= icon('stop'); ?></button></td>
        <td><button class="btn btn-danger"><?= icon('times'); ?></button></td>
    </tr>
<?php }
?>

Upvotes: 1

Related Questions