1

I have an array whick first key starts with one, and I need it like that.

//first iteration of $collections
$collections[1] = $data1;
$collections[2] = $data2;
...
//It does not have to start with zero for my own purposes

So I do the stuff needed like this:

//count($collections) = 56;
$collections = array_map(function($array)use($other_vars){
   //more stuff here

   //finally return:
   return $arr + ['newVariable'=$newVal];
},$collections);

When var_dump($collections); the first key is one, which is fine.

However, when I want to add another variable to the array like these:

//another array starting at one //count($anotherArray) = 56;
$anotherArray[] = ['more'=>'values'];

$collections = array_map(function($arr,$another)use($other_vars){
   //more stuff here

   //finally return:
   return $arr + ['newVariable'=$newVal,'AnotherVar'=>$another['key']];
},$collections,$anotherArray);

Then if I iterate $collections again, it now starts at zero. Why? How can I make it start from 1 instead of zero in the first key? Any ideas?

So why is the first key changed to zero? How can I keep it to be one?

You can reproduce the problem by executing the following code (for example on php online):

$collections[1]=['data1'=>'value1'];
$collections[2]=['data2'=>'value2'];
$collections[3]=['data3'=>'value3'];
$collections[4]=['data4'=>'value4'];

$another[1]=['AnotherData'=>'AnotherVal1'];
$another[2]=['AnotherData'=>'AnotherVal2'];
$another[3]=['AnotherData'=>'AnotherVal3'];
$another[4]=['AnotherData'=>'AnotherVal4'];

var_dump($collections);
echo '<hr>';
var_dump($another);

echo '<hr>';

$grandcollection=array_map(function($a){
    return $a + ['More'=>'datavalues'];
},$collections);

var_dump($grandcollection);

echo '<hr>';

$grandcollection2 = array_map(function($a,$b){
    return $a + ['More'=>'datavalues','yetMore'=>$b['AnotherData']];
},$collections,$another);

var_dump($grandcollection2);

Now adding the solution suggested by lerouche

echo '<hr>';
array_unshift($grandcollection2, null);
unset($grandcollection2[0]);
var_dump($grandcollection2);

It now does work as intended

Community
  • 1
  • 1
Pathros
  • 10,042
  • 20
  • 90
  • 156
  • 1
    `array_map()` ignores the original keys, it just processes the values and returns an array of the results. – Barmar May 17 '17 at 23:38
  • Array indexes normally start at 0. – Barmar May 17 '17 at 23:38
  • Possible duplicate of [how to change the array key to start from 1 instead of 0](http://stackoverflow.com/questions/5374202/how-to-change-the-array-key-to-start-from-1-instead-of-0) – mickmackusa May 18 '17 at 01:07

1 Answers1

2

After your $collections has been created, unshift the array with a garbage value and then delete it:

array_unshift($collections, null);
unset($collections[0]);

This will shift everything down by one, moving the first real element to index 1.

wilsonzlin
  • 2,154
  • 1
  • 12
  • 22