I want to access elements in an array generated by json_encode and want to be sure the element exists. To suppress a warning if it does not exist I use a @ prior:
1) When access path in array exists all works as expected
$test = @$obj['tag']
// result is "ABCD" if "ABCD" set, "" if "" and NULL if NULL => as
expected
2) When access path in array only partial exists Strings cause a problem
$test = @$obj['tag']['dddd']
// = "A" when ['tag'] = "ABCD", I understand that 'dddd' becomes an index of 0 in the array representing the string.
Any way to avoid this?
After trying out isset / is_scalar / is_null / empty I came to the followig conclusion for multidimensional arrays generated out of JSON data:
1) isset() does not distinguish between the value "null" with an existing key and a not existing key (I used @ for the access path to suppress warnings). "" strings are handled fine.
2) There is one anomaly if an access path contains a string. In this case the first character of the string will be the result. It does not matter how many dimensions come after the string. Will always reference the 0 index of the string array.
To avoid any problems I do now: 1) Use no null in JSON, what is a good idea anyway. 2) Avoid strings with a single char. If needed instead of Y/N using a boolean true/false could be used.
isset is_scalar is_null empty access path value
TRUE TRUE FALSE FALSE @$obj['tag']['dddd']['wwww'] A (not existing)
TRUE TRUE FALSE FALSE @$obj['tag']['dddd'] A (not existing)
TRUE TRUE FALSE FALSE @$obj['tag'] ABCD
TRUE TRUE FALSE FALSE @$obj['tagf'] ABCD
TRUE TRUE FALSE FALSE @$obj['user']['name'] Broemm
TRUE TRUE FALSE FALSE @$obj['user']['num'] 1234
FALSE FALSE TRUE TRUE @$obj['user']['num']['dddd'] (not existing)
TRUE TRUE FALSE TRUE @$obj['time']['b']['b'] “"
FALSE FALSE TRUE TRUE @$obj['time']['c']['b'] null
FALSE FALSE TRUE TRUE @$obj['tttt'] (not existing)
TRUE TRUE FALSE FALSE @$obj['boo'] 1
FALSE FALSE TRUE TRUE @$obj['boo']['qq'] (not existing)
FALSE FALSE TRUE TRUE @$obj['boo']['qq']['ee'] (not existing)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.