Alex Hu Alex Hu - 8 months ago 46
PHP Question

How to get only one result from foreach(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">
<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 ?>
<?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 ?>
<?php endforeach ?>


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.