Skip to content

PHP Number Array Element

Numbering an Array

In this case, we want to number a list of items in an array starting from 1.

  1. apple
  2. banana
  3. orange

But the problem is, the index of an array starts from 0. Here we use the following 2 ways to iterate elements of an array.

By Sequence

We may iterate the array sequentially to do the numbering with foreach. The simplest example is as such:

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

We retrieve the value one at a time.

By Index

The other way is to retrieve the real index number, if there were no other 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. Required fields are marked *