-2

how can I get first item from db by foreach

$posts = new Posts();    
$post = $posts->feature_post($conn);
foreach($post as $feature) { ?>

my html code is different for 1st item. so I need to get 1st item then other item, how I can do it?

thanks in advance.

  • Try to count the items as you handle them. – axiac Jun 19 '17 at 11:58
  • what is your ```$post``` variable structure? just wanted to know that's an ```array``` or ```object``` ? – Suresh Jun 19 '17 at 11:58
  • All this needs is a simple flag you set before the loop, and then check and flip inside ... `$first = true; foreach(...) { if($first) { dosomething(); } else { dootherstuff(); } $first = false; }` – CBroe Jun 19 '17 at 11:59

1 Answers1

1

To get the first item of an array, you can use the reset function

http://php.net/manual/fr/function.reset.php

<?php
$posts = new Posts();    
$listPost = $posts->feature_post($conn);
$firstPost = reset($listPost);
...

Also if you want to know if you loop through the first element and if the keys of your arrays are 0,1,2,3 etc..

<?php
foreach($array as $key => $cell) {
    if ($key === 0) {
        // this is your first element
        ....
    }
}

If the keys of your array are not numeric indexes but you don't intend to use them, you can obtain such array by using the array_values function

jiboulex
  • 2,963
  • 2
  • 18
  • 28