RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%
Leading Digital Marketing Experts | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.20% (5.24%*) • Home Loan Fixed: 5.48% (6.24%*) • Fixed: 5.48% (6.24%*) • Variable: 5.20% (5.24%*) • Investment IO: 5.74% (6.40%*) • Investment PI: 5.49% (6.32%*)

# 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.

E. Australia Standard Time [ UTC+10, Default ] [ CHECK TO CHANGE ]

Want to have a chat?

### How to Use the Abuse and Malware API

Some time back we had a website with an ‘unauthorised’ plugin introduce sophisticated Malware into a website that resulted in

### How to Use the Telephone Abuse and Resolution API

There’s no easy way to stop spam and scam phone calls. We looked at building a mobile application that’d rely

### Elementor Forms Integrated With Yabber Automation

We provide a large number of forms via Yabber integration, meaning that lead forms, event forms, referral forms, fact find