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 st
In php Use this
'Month'=> [ 1 => "January","February","March","April","May","June","July","August","September","October","November","December"],
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
)
I think it is simple as that:
$x = array("a","b","c");
$y =array_combine(range(1, count($x)), $x);
print_r($y);
Ricardo Miguel's solution works best when you're defining your array and want the first key to be 1. But if your array is already defined or gets put together elsewhere (different function or a loop) you can alter it like this:
$array = array('a', 'b', 'c'); // defined elsewhere
$array = array_filter(array_merge(array(0), $array));
array_merge
will put an array containing 1 empty element and the other array together, re-indexes it, array_filter
will then remove the empty array elements ($array[0]
), making it start at 1.
$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
$array = array('a', 'b', 'c', 'd');
$array = array_combine(range(1, count($array)), array_values($array));
print_r($array);
the result:
Array
(
[1] => a
[2] => b
[3] => c
[4] => d
)