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

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);

Download


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 • Version 0.2, 494.0B, zip, Category: PHP Code & Snippets

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?
 

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment

READY TO HAVE A CHAT? CALL US ANYTIME ON 1300 235 433