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
  • 55,591
  • 6
  • 41
  • 52
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,748
  • 6
  • 35
  • 57
1

try this..

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

and no need to use multiple php tags...

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