Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simplify array value initialization

Several times a day I run into a problem where I need to dynamically initialize variables in a multidimensional array to prevent PHP throwing a notice because of an uninitialized variable.

Code fragments like this are very common:

if(!isset($profile[$year][$month][$weekday][$hour])) {
    $profile[$year][$month][$weekday][$hour] = 0;
}
$profile[$year][$month][$weekday][$hour] += $load;

Or:

$profile[$year][$month][$weekday][$hour] 
    = isset($profile[$year][$month][$weekday][$hour]) 
    ? $profile[$year][$month][$weekday][$hour] + $load
    : $load;

That looks awful and is a pain to write, also makes maintaining quite hard as these fragments are abundant. Does anyone have any ideas how I could simplify such a task? I thought of creating a reference $r to $profile[$year][$month][$weekday][$hour] to reduce redundancy, but it will also throw a notice if not initialized properly.

Initializing the array beforehand isn't feasible as not all keys will be used and I'd like to avoid unnecessary keys.

Any tips?

like image 957
Tatu Ulmanen Avatar asked May 14 '26 07:05

Tatu Ulmanen


1 Answers

I asked the same question a few months back and got a number of good answers.

In your case, maybe set up a generic function?

Something like:

set_array_member (&$profile, $year, $month, $weekday, $hour, 0);

$result = get_array_member (&$profile, $year, $month, $weekday, $hour);

the parameter before last being the member to be set, and the last the value (or something like that, you get my drift.) You could use func_get_args() to keep the parameter count flexible.

like image 145
Pekka Avatar answered May 15 '26 22:05

Pekka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!