Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggregation Enquires Welcome

Example Interest Rates: Home Loan Variable: 2.54% (2.74%*) • Home Loan Fixed: 3.74% (3.8%*) • Fixed: 2.48% (2.94%*) • Variable: 2.54% (2.74%*) • Investment IO: 2.3% (3.76%*) • Investment PI: 2.04% (3.8%*)

# 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 re-index 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 that we were repeatedly applying the code in a project, so it made sense.

### An Example

Consider the following simple array:

1
\$arr = array('0' => 'a', '1' => 'b', '2' => 'c', '3' => 'd', '4' => 'e');

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

1
<?php
2
\$newarray = beliefmedia_index_array(\$arr);
3
print_r(\$newarray);

The result:

1
\$arr = array('1' => 'a', '2' => 'b', '3' => 'c', '4' => 'd', '5' => 'e');

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.

1
<?php
2
\$newarray = beliefmedia_index_array(\$arr, \$one = false);
3
print_r(\$newarray);

### The PHP Function

1
<?php
2
function beliefmedia_index_array(\$arr, \$one = true) {
3
return (\$one) ? array_combine(range(1, count(\$arr)), array_values(\$arr)) : array_values(\$arr);
4
}

Of course you could just use the following to re-index 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.

1
\$newarray = array_combine(range(1, count(\$arr)), array_values(\$arr));

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

1
\$newarray = array_values(\$arr);

Title: Index PHP Array so first value is 1
Description: Index a PHP Array so the first value has a numeric Key of 1 (rather than 0).

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients. AUS Eastern Standard Time (Washington)

Want to have a chat? 