1

First post here, and a new PHP developer. :x I'm looking for a way to iterate through the LAST four elements of an array, then break. The array keys are custom IDs for the products sold on a website, so I can have the flexibility of adding additional items and have it show the four newest items dynamically on the main page. I almost had it using array_reverse, until I realized that it cleared the custom keys.

Is there an easier way that I could be doing this?

    <?php
        $products_reverse = array_reverse($products);
        $count = 0;

            while ($count < 4) {
                foreach ($products_reverse as $product) {
                    $shirt_id = key($product);
                    echo "<li>";
                    echo '<a href="' . 'shirt.php?id=' . $shirt_id . '">';
                    echo '<img src="img/shirts/shirt-' . $shirt_id . '.jpg"> </a>';
                    echo '<p>View Details</p>';
                    echo '</li>';
                    $count++;
                }
           }
    ?>
manlio
  • 18,345
  • 14
  • 76
  • 126
capecoder
  • 23
  • 8
  • Thanks - while digging through PHP forums and SO, I found a few problems with my code. _array_slice_ should fix my issue with retaining keys, and my iterations were also broken. It looks like this should work once I get my arguments set correctly. – capecoder Jun 16 '15 at 05:25

1 Answers1

2

use array_slice

$latest_arr = array_slice($products, 3);

Edit : To preserve keys by the way, set the fourth argument to true

Anonymous Duck
  • 2,942
  • 1
  • 12
  • 35