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 } ?> 
1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

$first = array_values($category['transactions')[0] 

8 Comments

And you don't even need to copy the complete array, just use reset().
Interesting. I've never seen that before. Thanks.
I've added some html code. Would you please base on my example and tell where I should paste your code?
@user2699714 Try doing the anwser below. Which is the same thing that Markus Malkusch has said.
@user2699714 Just place the div tags right around <?php echo array_values($category['transactions')[0] ?> and remove the foreach loop or put this before it.
|
1

try this..

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

and no need to use multiple php tags...

1 Comment

@MarkusMalkusch .. Ohh yeah.. In hurry I put that round brackets let me edit my answer..Thanks..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.