How to simplify the initialization of an array value

Several times a day, I run into a problem when I need to dynamically initialize variables in a multidimensional array to prevent PHP from being thrown out due to 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;

It looks horrible and is a pain to write, and also makes preservation quite tough, as these fragments are plentiful. Does anyone have any ideas how I could simplify such a task? I was thinking of creating a to link $rto $profile[$year][$month][$weekday][$hour]reduce redundancy, but it will also generate a notification if it was not properly initialized.

Initialization of the array is not possible in advance, since not all keys will be used, and I would like to avoid unnecessary keys.

Any tips?

+3
2

.

, , ?

- :

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

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

, , ( - , .) func_get_args(), .

+1

, if(isset($r)), , :)

, ( , ) .

0
source

Source: https://habr.com/ru/post/1735034/


All Articles