array-index

Index a PHP Array so the first value has a numeric Key of 1 (rather than 0)

If you find yourself with the need to reindex an array so the first element has a key of 1 (rather than 0), the following function may come in useful. The function certainly isn’t required… it’s just I was repeatedly applying the code in a project so it made sense.

An Example

Consider the following simple array:

If I wanted the first value (a) with a key of 1, I’d apply the following:

The result:

If I had an array with the first key of a higher value, you can use the following to reset the first key to a value of zero.

The PHP Function

Of course you could just use the following to reindex the array so the first value has a key of ‘1’. It’s certainly easier to apply if you only require the result in transient.

If you wanted to re-index starting at zero, just use the following:

Shortt URL for this post:

Leave a Reply

Your email address will not be published. Required fields are marked *