RBA Cash Rate: 4.35% · 1AUD = 0.71 USD · Inflation: 4.6%  
Leading Digital Marketing Experts | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.24% (5.24%*) • Home Loan Fixed: 5.70% (6.06%*) • Fixed: 5.70% (6.06%*) • Variable: 5.24% (5.24%*) • Investment IO: 5.69% (5.72%*) • Investment PI: 5.49% (5.52%*)

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: E. AUSTRALIA STANDARD TIME · [ CHANGE ]

Related Articles:

John Snow Cholera Map, 1854

The Xena Statistical Engine

The level of statistical integration availed to those that use Yabber (and our broker website) was always industry leading. However, with over 100 modules that

Read More »
RBA Building, Sydney, 6 February 1963

The RBA API

The Reserve Bank of Australia (RBA) publishes large amounts of data to its website as Excel Spreadsheets, but this method makes advanced queries and analytics

Read More »

Like this article?

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