0

I have an array $category['transactions']. It stores data as follow:

ID   Name  Phone
1   Test   Test2
2   Test3  Test4

It's because I use the same array for different purpose, at one of the scenario is to show only the first record in this array. I don't what to change the coding in php nor creating a different parameter. What can I improve based on the following coding in html to get the first record only in this array?

                    <?php foreach($category['transactions'] as $transaction) { ?>
                            <div><?php echo $transaction['id']; ?></div>
                            <div><?php echo $transaction['name']; ?></div>
                    <?php } ?>

3 Answers3

3

replace your code with.

<?php $firstRow=reset($category['transactions']);
    echo '<div>',$firstRow['id'],'</div>';
    echo '<div>',$firstRow['name'],'</div>';
?>

You don't need to iterate through the array to get the first element.

bansi
  • 52,760
  • 6
  • 38
  • 48
2

You don't even need the foreach to get the first element. Just use array_values():

$first = array_values($category['transactions')[0]
Anonymous
  • 11,347
  • 6
  • 32
  • 56
1

try this..

<?php foreach($category['transactions'] as $transaction) { echo $transaction['id']; break; } ?>

and no need to use multiple php tags...

Nishant Solanki
  • 2,140
  • 3
  • 19
  • 32