robins
robins

Reputation: 1668

How to get the first data in iteration in PHP

I have a list of data. I need to add the first one as the title.

How can I get the first one and add the property for heading.

View

  <ul class="list-group">  
  <? foreach($job_details->result() as $value) { ?>
            <li class="list-group-item m-xs">
            <span class="badge badge-primary"><?echo $value->job_value;?></span>                        
            </li>
  <?}?>  
  </ul> 

Upvotes: 2

Views: 107

Answers (3)

Rajat Gupta
Rajat Gupta

Reputation: 340

    <ul class="list-group">  
    <?php $data=$job_details->row_array();
     $value=reset($data);
     ?>
        <li class="list-group-item m-xs">
        <span class="badge badge-primary"><?php echo $value->job_value;?>
        </span>                        
        </li>

      </ul>

Use row_array for one row fetch

Upvotes: -1

AGM Tazim
AGM Tazim

Reputation: 2217

Its very easy. Just get your first index from array returned from $job_details->result().

 <ul class="list-group">  
       <?php 
           $data = $job_details->result();

           if($data){
                 if(isset($data[0])){ ?>
                     $header = $data[0]; //  or $header=$data['first-index']; // get your first value from array . 

                    <li class="list-group-item m-xs">
                    <span class="badge badge-primary"><?php echo $header;?> //or echo $header->desiredvalue;  </span>                  

                    </li>

        <?php }} ?>

  </ul>

Upvotes: 0

Oscar P&#233;rez
Oscar P&#233;rez

Reputation: 4397

The best solution would be to put your data in an array and then get the first result:

<ul class="list-group">  
<?php $data=$job_details->result();
     $value=reset($data);
 ?>
        <li class="list-group-item m-xs">
        <span class="badge badge-primary"><?php echo $value->job_value;?>   </span>                        
        </li>

</ul>

Just a sidenote: don't use PHP short open tags (<?).

Upvotes: 3

Related Questions