Skip to content

How To Number an Array in FOREACH Loop

If you want to number a list of items from an array like this:

  1. apple
  2. banana
  3. orange

You may use the index number of an array to do the numbering with foreach. The simplest syntax is as such:

$i = 0;
foreach ($arr as $value) {
    echo $i++;
    echo $value;
}

You can retrieve the value one at a time.

The other syntax can retrieve the real index number, if there were no literal keys in the array.

foreach ($arr as $idx => $value) {
    echo $idx + 1;
    echo $value;
}

It can be very flexible to design your web page. But don't forget that the starting index number of an array is 0.

Leave a Reply

Your email address will not be published.