mehdi mehdi - 1 year ago 134
PHP Question

How to determine the first and last iteration in a foreach loop?

The question is simple. I have a

loop in my code:

foreach($array as $element) {

In this loop, I want to react differently when we are in first or last iteration.

How to do this?

Answer Source
  1. You could use a counter:

    $i = 0;
    $len = count($array);
    foreach ($array as $item) {
        if ($i == 0) {
            // first
        } else if ($i == $len - 1) {
            // last
        // …
  2. Your method requires a database query for every single collection, category and subcategory. So if you have 10 collections, 100 categories and 1000 subcategories, you will have at least 1110 database queries.

    You should try to do it with just one query (see table joins) or at least one query per table.

  3. A proper used list is always better than a div soup. So try to use ul and li.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download