When we write the traversal array, there are several methods, such as $ arr [\ 'key \ '], $ arr [\ "key \"], and $ arr [key ]. outgoing content, but where are their differences? Let me introduce them below.
I. Differences between $ arr ['key'] and $ arr ["key"] and $ arr [key:
The above three methods mainly access the array value through the string type array subscript, that is, the array key. If the array subscript is an index type, that is, the key value is a number, you do not need to pay attention to it.
1, $ arr ['key'] the single quotation mark mode is directly parsed as the value of $ arr;
2. $ arr ["key"] in double quotation mark mode, the system first analyzes whether the "key" string contains the PHP variable and then parses it into the value of $ arr;
3, $ arr [key] without any quotation marks, it will first analyze whether there is a key constant definition in the local scope (that is, there is no define ('key', 'val ')),
If yes, use the constant value represented by a local key constant as the array key value;
Otherwise, continue to analyze whether the key constant definition is in the global scope,
If yes, the constant value represented by the global key constant is used as the array key value;
Otherwise, an E_NOTICE exception is thrown when the internal conversion key is a 'key' string scalar value.
Ii. Differences between $ arr ["$ str_key"] and $ arr [$ str_key]
This method also accesses the value of the array through the subscript of the string type array,
If the array subscript is an index, that is, a number, you do not need to pay attention to it.
In fact, no extra double quotation marks are required to indicate that the $ str_key variable represents the string value,
That is, $ arr ["$ str_key"] ===$ arr [$ str_key]
The Code is as follows: |
Copy code |
<? Php Define ('constant', 'arr1 '); $ Constant = 'arr2 '; $ Variable = 'arr1 '; $ Arr = array ( 'Arr1' => 'arr1 ', 'Arr2 '=> 'arr2 ', 'Arr3 '=> 'arr3 ', ); Echo $ arr ['arr1 '],' <br/> ', $ arr ["$ variable"],' <br/> ', $ arr [constant], '<br/>', $ arr [$ constant]; ?> |