Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get only one result from foreach(PHP)

Tags:

php

The code loop an array and display all views for a user. Now things changed and I just need to display one result from a foreach loop. How do I do that?

<table class="report_edits_table">
<thead>
  <tr class="dates_row">
  <?php foreach($report['edits'] as $report_edit) : ?>
    <td colspan="2" report_edit_id="<?php echo $report_edit['id'] ?>"><div class="date_container">
    <?php if($sf_user->hasCredential(Attribute::COACHING_EDIT_ACCESS)) : ?>
      <span class="ui-icon ui-icon-trash">Remove</span>
    <?php endif?>
    <?php echo "View " . link_to($report_edit['created'], sprintf('coaching/viewReportEdit?reportedit=%s', $report_edit['id']), array('title' => 'View This Contact')) ?> </div></td>
  <?php endforeach ?>
  </tr>
</thead>
<tbody>
  <?php foreach($report['edits_titles'] as $index => $title) : ?>
  <tr class="coach_row">
    <?php for ($i=max(0, count($report['edits'])-2); $i<count($report['edits']); $i++) : $report_edit = $report['edits'][$i] ?>
    <td class="name_column"><?php echo $title ?></td>
    <td class="value_column"><?php echo $report_edit[$index] ?></td>
    <?php endfor ?>
  </tr>
  <?php endforeach ?>
</tbody>

like image 334
Alex Hu Avatar asked Dec 07 '22 19:12

Alex Hu


1 Answers

Use the break command for simple conversion:

<?php for ... ?>
    ... stuff here ...
    <?php break; ?>
<?php endfor ... ?>

A better solution would be to remove the foreach completely.

like image 165
mellamokb Avatar answered Dec 10 '22 12:12

mellamokb