PHP autovivification -
update: original intention question determine if php has feature. has been lost in answers' focus on scalar issue. please see new question instead: "does php have autovivification?" question left here reference.
according wikipedia, php doesn't have autovivification, yet code works:
$test['a']['b'] = 1; $test['a']['c'] = 1; $test['b']['b'] = 1; $test['b']['c'] = 1; var_dump($test); output:
array 'a' => array 'b' => int 1 'c' => int 1 'b' => array 'b' => int 1 'c' => int 1 i found code works too:
$test['a'][4] = 1; $test['b'][4]['f'] = 3; but adding line causes warning ("warning: cannot use scalar value array")
$test['a'][4]['f'] = 3; what's going on here? why fail when add associative element after index? 'true' perl-like autovivification, or variation of it, or else?
edit: oh, see error scalar now, oops! these work expected:
$test['a'][4]['a'] = 1; $test['a'][4]['b'] = 2; $test['a'][5]['c'] = 3; $test['a'][8]['d'] = 4; so, php have autovivification? searching google "php autovivification" doesn't bring canonical answer or example of it.
from php manual on square bracket syntax:
$arr[] = value;if
$arrdoesn't exist yet, created, alternative way create array
with example:
$test['a'][4] = 1; since $test , $test['a'] don't exist; both created arrays.
$test['b'][4]['f'] = 3; $test['b'] , $test['b'][4] don't exist; both created arrays.
$test['a'][4]['f'] = 3; $test['a'][4] does exist, integer (1). "scalar value" cannot used array. can't use square bracket [] syntax on number values; doesn't convert existing value array.
Comments
Post a Comment