Reputation: 43
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 } ?>
Upvotes: 0
Views: 138
Reputation: 57002
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.
Upvotes: 3
Reputation: 12017
You don't even need the foreach to get the first element. Just use array_values()
:
$first = array_values($category['transactions')[0]
Upvotes: 2
Reputation: 2128
try this..
<?php
foreach($category['transactions'] as $transaction)
{
echo $transaction['id'];
break;
}
?>
and no need to use multiple php tags...
Upvotes: 1