The [(subscript)] symbol in PHP can be applied not only to arrays and objects, but also to strings, and is prone to errors if not noticed.
For example, to obtain a network interface, normally returns a JSON of the array structure, after parsing the result is:
Array (' content ' = ' This is returned by interface ')
After we have obtained the interface data, we have a problem with the following statement to determine if the content has values:
if (!empty ($result [' content ')]) echo $result [' content '];
Because, however, if the server is an exception, the following HTML string may be returned:
In this case, after Json_decode parsing, if we use the above statement, we will get a < character, which is why?Let's take a look at the logic in PHP5.2.5 [] that acts on strings:
... case is_string: {zval tmp; if (Dim = = NULL) {Zend_error_noreturn (E_error, "[] operator not supported for strings"); } if (z_type_p (Dim) = Is_long) {switch (z_type_p (Dim)) { /* Case Is_long: */Case Is_string:case IS_DOUBLE:C ASE is_null:case Is_bool:/* do nothing */b Reak; Default:zend_error (e_warning, "illegal offset type"); Break } tmp = *dim; Zval_copy_ctor (&TMP); Convert_to_long (&TMP); Dim = &tmp; } switch (type) {case Bp_var_r:case BP_var_is:case bp_var_unset:/* do nothing ... */break; Default:separate_zval_if_not_ref (CONTAINER_PTR); Break } if (result) {container = *container_ptr; Result->str_offset.str = container; Pzval_lock (container); Result->str_offset.offset = z_lval_p (Dim); Result->var.ptr_ptr = NULL; if (type = = Bp_var_r | | type = = bp_var_is) {ai_use_ptr (Result->var); }} return; } Break, ...
The above source: Dim denotes subscript;First, the judgment is not the [] operator is not subscript, if it is an error. Because there is no subscript, is to add a word group, which for the string must be wrong.
Then judge whether the subscript is a digital type, please note 1234 and "1234", PHP will be considered to be a digital type. If it is not a numeric type, the subscript will be converted to a numeric type, and the string will be converted to 0 under this conversion rule;
So, in the example above, when you access the data labeled content, you return the data labeled 0, which is the < character.
So, strictly speaking, when accessing an array subscript, it is necessary to first determine whether this type is an array type, to ensure foolproof.
PHP uses subscript notation [] to read the logic of a string