Home > Article > Backend Development > How to define array in PHP? How many ways are there to define an array?
PHP array is actually an ordered map. PHP ArrayMapping 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. Since the value of a PHP array element can also be another array, tree structures and multidimensional arrays are also allowed.
Generally speaking, the definition methods are as follows:
Method 1:
$a=array('a','b','c');
The running results are as follows shown.
Array
(
[0]=>a
[1]=>b
[2]=>c
[3]=>simon
)
Method 2:
$a=array(key1=>value1,key2=>value2,key3=>value3);
Method 3:
$a[key1]=value1; $a[key2]=value2;
Method 4: Through square brackets [ ]Define array
You can write like this after php version 5.4, with the new array abbreviation syntax.
php version 5.3 and previous versions do not accept writing like this...
$data = [ 'start_time' => '123', 'end_time' =>'456' ];
Syntax
Define array array()
You can use the array() language structure to create a new array. It accepts any number of comma-separated key => value pairs.
array( key => value, ... ) // 键(key)可是是一个整数 integer 或字符串 string // 值(value)可以是任意类型的值
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.
Since 5.4, you can use short array definition syntax, using [] instead of array().
PHP arrays are relatively simple and convenient to use, and the calling is equally simple and convenient. They are suitable for large, medium and small data storage and calling
Related recommendations:
Several ways to delete elements with specified values in php arrays
php array replacement function array_replace()
php array to string to obtain array representation of the path method analysis
The above is the detailed content of How to define array in PHP? How many ways are there to define an array?. For more information, please follow other related articles on the PHP Chinese website!