<?php
$players = [
[
'name' => 'ronaldo',
'quality' => 'best plaeyr'
],
[
'name' => 'scholes',
'quality' => 'respected'
],
[
'name' => 'mbaape',
'quality' => 'fastest'
]
];
?>
this is my $players array
This is how i printed out the list of names
<?php foreach ($players as $player) : ?>
<li> <?= $player['name']?> </li>
<?php endforeach ?>
this works well, but how do i echo out like the first name in the list, like ronaldo
specifically and not all the names like in the loop above.
tried this
<?php foreach ($players as $player) : ?>
<?php
if($players[0])
{
echo $player['name'];
};
?>
but this just prints out all 3 names not just the first one that i need i.e. ronaldo
.
4
Answers
You can use
reset
for this. It works for associative array as well.Live Demo
There are several ways to do that:
reset
function as suggested bynice_dev
.Stopping Loop
Printing first name directy
Instead of a loop you could just check whether
$players
is indeed an array and has element, in which case you can echo the name of the 0’th item.You can use a
for
loop with an index:If you only really need the first element, then you do not need a loop at all, you’re fine by just referring the name of the 0’th element, like
$players[0]["name"]
. But it’s good to know that there is a way to conditionally do something in the loop for cases that actually require a loop, like echoing paired indexed elements or so.