Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change the array key to start from 1 instead of 0

Tags:

arrays

php

I have values in some array I want to re index the whole array such that the the first value key should be 1 instead of zero i.e.

By default in PHP the array key starts from 0. i.e. 0 => a, 1=> b, I want to reindex the whole array to start from key = 1 i.e 1=> a, 2=> b, ....

like image 205
Khurram Ijaz Avatar asked Mar 21 '11 05:03

Khurram Ijaz


People also ask

How can we change the starting index of an array from 0 to 1?

Explanation: No. You can not change the C Basic rules of Zero Starting Index of an Array.

How do you make an array index start from 1?

Base Index of Java arrays is always 0. It cannot be changed to 1.

How do you change the start index of an array?

To change the position of an element in an array:Use the splice() method to insert the element at the new index in the array. The splice method changes the original array by removing or replacing existing elements, or adding new elements at a specific index.


2 Answers

$alphabet = array("a", "b", "c"); array_unshift($alphabet, "phoney"); unset($alphabet[0]); 

Edit: I decided to benchmark this solution vs. others posed in this topic. Here's the very simple code I used:

$start = microtime(1); for ($a = 0; $a < 1000; ++$a) {     $alphabet = array("a", "b", "c");     array_unshift($alphabet, "phoney");     unset($alphabet[0]); } echo (microtime(1) - $start) . "\n";   $start = microtime(1); for ($a = 0; $a < 1000; ++$a) {     $stack = array('a', 'b', 'c');     $i= 1;     $stack2 = array();     foreach($stack as $value){         $stack2[$i] = $value;         $i++;     }     $stack = $stack2; } echo (microtime(1) - $start) . "\n";   $start = microtime(1); for ($a = 0; $a < 1000; ++$a) {     $array = array('a','b','c');      $array = array_combine(         array_map(function($a){             return $a + 1;         }, array_keys($array)),         array_values($array)     ); } echo (microtime(1) - $start) . "\n"; 

And the output:

0.0018711090087891 0.0021598339080811 0.0075368881225586 
like image 133
Michael McTiernan Avatar answered Oct 12 '22 23:10

Michael McTiernan


Here is my suggestion:

<?php $alphabet = array(1 => 'a', 'b', 'c', 'd'); echo '<pre>'; print_r($alphabet); echo '</pre>'; ?> 

The above example will output:

Array (     [1] => a     [2] => b     [3] => c     [4] => d ) 
like image 44
Ricardo Miguel Avatar answered Oct 12 '22 21:10

Ricardo Miguel