skip to Main Content
<?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


  1. You can use reset for this. It works for associative array as well.

    <?php
    
    echo reset($players)['name'];
    

    Live Demo

    Login or Signup to reply.
  2. There are several ways to do that:

    • Stop the loop after the first run.
    • Print the first name directly without using a loop.
    • Consider using the reset function as suggested by nice_dev.

    Stopping Loop

    foreach ($players as $player)
    {
        echo $player['name'];
        break;
    }
    

    Printing first name directy

    echo $players[0]['name'];
    
    Login or Signup to reply.
  3. 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.

    <?php if( is_array( $players ) && 0 < count( $players ) ) { echo $players[0]['name']; }
    
    Login or Signup to reply.
  4. You can use a for loop with an index:

    for ($index = 0; $index < count($players); $index++) {
        if ($index === 0) echo $players[$index]["name"];
    }
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search