Mathias Hillmann
Mathias Hillmann

Reputation: 1837

Access current array key while setting value

I have the following array that is filled three times:

$forecast[] = [
    'forecast' => $calculatedForecast,
];

To produce the following array:

[
   [
      'forecast' => 10,
   ],
   [
      'forecast' => 20,
   ],
   [
      'forecast' => 30,
   ],
]

However I need to access the current array key to set in a internal value like this:

$forecast[] = [
    'period' => $array_key,
    'forecast' => $calculatedForecast,
];

To create the following array:

[
   [
      'period' => 0,
      'forecast' => 10,
   ],
   [
      'period' => 1,
      'forecast' => 20,
   ],
   [
      'period' => 2,
      'forecast' => 30,
   ],
]

While i could include a $i = 0 and 'period' => $i++,, I would prefer to do this in a more elegant way. Is this possible?

Upvotes: 0

Views: 37

Answers (1)

Yoshi
Yoshi

Reputation: 54659

With code like this:

$forecast[] = [
    'forecast' => $calculatedForecast,
];

the right side will execute before the assignment. At that moment the next index is just the current number of elements in the array. So:

$forecast[] = [
    'period'   => count($forecast),
    'forecast' => $calculatedForecast,
];

will work.


Note though, that depending on the context in which this code executes keeping track of the next index like you described in your question ($i++) might be the better option.

Upvotes: 1

Related Questions