Reputation: 13527
Consider:
$snode->field_length = array();
$snode->field_length['und'] = array();
$snode->field_length['und'][0] = array();
$snode->field_length['und'][0]['value'] = 5;
Versus just writing:
$snode->field_length['und'][0]['value'] = 5;
In the second case, you are assigning to fields that don't exist. However, PHP doesn't complain. Does that mean it's okay to code like this?
Upvotes: 2
Views: 89
Reputation: 393
Yes, it is ok, but maybe is not the clearest way to write it.
PHP has dynamic typing, so it is not necessary to specify the type of a variable before using it, because the interpreter is responsible for inferring what type you're trying to assign at runtime.
I would consider using array intializers:
$snode->field_length = array(
'und' => array(
array(
'value' => 5
)
)
);
Or, even better, in PHP >= 5.4:
$snode->field_length = [
'und' => [
[
'value' => 5
]
]
];
Upvotes: 4
Reputation: 68
Yes, you can do as @mchurichi answers says but if there's the case, when you don't know the previous value, use array_merge or array_merge_recursive:
if(!is_array($snode->field_length)){
$snode->field_length = array();
}
$snode->field_length = array_merge_recursive($snode->field_length, array(
'und' => array(
array(
'value' => 5
)
)
));
Upvotes: 1