RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts</strong | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.69% (5.89%*) • Home Loan Fixed: 5.39% (6.59%*) • Fixed: 5.39% (6.59%*) • Variable: 5.69% (5.89%*) • Investment IO: 5.69% (6.48%*) • Investment PI: 5.39% (6.59%*)

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

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 complimentary 650-page guide on marketing for mortgage brokers. We'll show you exactly how we generate billions in volume for our clients.
Finance Guide, Cropped Top and Bottom
  Timezone: 1 · [ CHANGE ]

RELATED READING

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment