Home >Backend Development >PHP Tutorial >JavaScript Data Types PHP Section 2 Array of Data Types
Array in PHP is actually an ordered map. A mapping is a type that associates values to keys. This type is optimized in many ways, so it can be treated as a real array, or list (vector), hash table (which is an implementation of map), dictionary, set, stack, queue and many more possibilities. The value of an array element can also be another array. Tree structures and multidimensional arrays are also allowed.
You can use thearray() language structure to create a new array. It accepts any number of comma-separated key => value pairs.
key can be integer or string. If key is the standard representation of a integer, it is interpreted as an integer (e.g. "8" will be interpreted as 8, and "08" will be interpreted as "08"). Floating point numbers in key are rounded to integer. In PHP, indexed arrays are the same as associative arrays, they can both contain subscripts of integers and strings.
The value can be any PHP type. If no key is specified for the given value, the current largest integer index value will be taken, and the new key will be that value plus one. If the specified key name already has a value, the value will be overwritten. UsingTRUE as the key name will make
integer1 the key name. Using FALSE as the key name will make
integer0 the key name. Using NULL as a key name will be equivalent to using the empty string. Using an empty string as a key will create (or overwrite) a value with an empty string as the key, which is different from using empty square brackets.
Illegal offset type.
Use square bracket syntax to create/modifyIf$arr does not exist yet, a new one will be created. This is also an alternative way of defining an array. To change a value, just assign it a new value. If you want to delete a key/value pair, use unset() on it.
Note: If square brackets are given but no key name is specified, the current maximum integer index value is taken and the new key name will be that value + 1. If there is no integer index currently, the key name will be 0. If the specified key name already has a value, the value will be overwritten.
Note that the maximum integer key name used hereis not necessarily currently in the array. It just needs to have existed since the last time the array was reindexed.
You should always put quotes around array indices expressed as strings. For example, use $foo['bar'] instead of $foo[bar]. But why is $foo[bar] wrong? The reason is that there is an undefined constant (bar) in this code instead of a string ('bar' - note the quotes), and PHP may define this constant later, unfortunately you have the same name in your code . It works because PHP automatically converts anaked string (a string without quotes and not corresponding to any known symbol) into a normal string whose value is that bare string. For example, if there is no constant defined as bar, PHP will replace it with
'bar' and use that.