Home >Backend Development >PHP Tutorial >Arrays in PHP
Overview
An array in PHP is actually an ordered map. A map is a type that associates values to keys.
PHP arrays can contain both integer and string key names, because PHP does not actually distinguish between indexed arrays and associative arrays.
The key can be an integer or a string string
The value can be any type of value
There are two ways to define an array
You can use the array() language structure to create a new array
<code>array( key => value , ... ) </code>
Since 5.4, you can use the short array definition syntax, use [ ] Replace array()
The comma after the last array element can be omitted. Usually used in single-line array definitions, such as array(1, 2) instead of array(1, 2, ). It is common to leave the last comma in multi-line array definitions to make it easier to add a new cell.
The key of the arrayThe key (key) can be an integer or a string string
In addition, the key will have the following forced conversion
Strings containing legal integer values will be converted to integers. For example, the key name "8" will actually be stored as 8. But "08" will not be cast because it is not a legal decimal value.If no key name is specified for the given value, the current largest one will be used. Integer index value, and the new key name will be this value plus one; if there is no integer index currently, the key name will be 0.
foo['bar'] and $foo[bar]For $foo[bar], if there is no constant defined as bar, PHP will replace it with 'bar' and use it
Array traversal
The foreach syntax structure provides a simple way to traverse the array. foreach can only be applied to arrays and objects.
There are two syntaxes:
<code>foreach (array_expression as $value) statement foreach (array_expression as $key => $value) statement </code>unset()
unset() function allows to delete a key in the array. But be aware that the array will not be reindexed. If you need to delete and rebuild the index, you can use the array_values() function.
<code>$a = array(1 => 'one', 2 => 'two', 3 => 'three'); unset($a[2]); /* will produce an array that would have been defined as $a = array(1 => 'one', 3 => 'three'); and NOT $a = array(1 => 'one', 2 =>'three'); */ $b = array_values($a); // Now $b is array(0 => 'one', 1 =>'three') </code>Array function
http://php.net/manual/zh/ref.array.php
The above has introduced arrays in PHP, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.