3

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?

Tatu Ulmanen
  • 123,288
  • 34
  • 187
  • 185

2 Answers2

1

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.

Community
  • 1
  • 1
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • Good idea. I need this to work on several different types on arrays, so your idea of using `func_get_args()` is good, but how can you check if the given key exists or not when you have the keys in an array? I can't think of any fast methods, any ideas? – Tatu Ulmanen Mar 02 '10 at 12:52
  • @Tatu I was thinking along the lines of something like `if isset($args[0][$args[1]][$args[2]][$args[3]] .....` but this is indeed tricky to do with the dynamic number of arguments. Who is going to be first to say the e-word? :) – Pekka Mar 02 '10 at 12:59
  • 1
    @Tatu Maybe a loop using `array_key_exists()`? That could work. If I find the time to put some more reasoning it later, I'll update the answer. Let me know if you get anywhere with this. – Pekka Mar 02 '10 at 13:06
0

The reference idea is good, and its easier to write if(isset($r)) than what you have right now :)

That said, the only other way around this off the top of my head is (and its terrible practice and I don't recommend it) turn off notices.

Alex Weber
  • 2,186
  • 2
  • 19
  • 27
  • Yea, but defining the reference will cast a notice if the referenced variable doesn't exist, so I won't even get to the `isset()` part without a notice. – Tatu Ulmanen Mar 02 '10 at 12:45