Reverse array with custom keys, keep keys intact?

229 views Asked by At

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++;
                }
           }
    ?>
1

There are 1 answers

7
Anonymous Duck On BEST ANSWER

use array_slice

$latest_arr = array_slice($products, 3);

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