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++;
                }
           }
    ?>
1
  • 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. Commented Jun 16, 2015 at 5:25

1 Answer 1

2

use array_slice

$latest_arr = array_slice($products, 3);

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

Sign up to request clarification or add additional context in comments.

7 Comments

Are you sure it's not -3 though?
@Hassan im not solving the problem, let her, dont spoon feed
Well, I think that should have been stated then. +1 regardless.
Ok, I now have a nice, neat block that returns the last four products of the array! There doesn't appear to be an argument to pass to reverse them in order, however, and reversing the array slice would bring me back to my initial problem.
just use both functions
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.