3 methods: 1. Use "[]" to assign values to elements individually, the syntax is "$array variable name [subscript] = value;"; 2. Use "[]" to initialize all elements together, Syntax "$array variable name = [key value list];"; 3. Use array() to initialize all elements together, syntax "$array variable name = array (key value list)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
3 methods of php array initialization
Method 1: Assign values to the elements in the array individually
$数组变量名[下标] = 值;
The subscript (index value) can be a string or an integer, and the subscript needs to be wrapped with []
.
<?php header("Content-type:text/html;charset=utf-8"); $a["color"]="red"; $a["taste"]="sweet"; $a["shape"]="round"; $a["name"]="apple"; $a[3]=4; var_dump($a); ?>
The subscript can be omitted, and the index value will increase sequentially starting from 0 by default.
<?php header("Content-type:text/html;charset=utf-8"); $a[]="red"; $a[]="sweet"; $a[]="round"; $a[]="apple"; $a[]=4; var_dump($a); ?>
Method 2: Use []
to initialize all elements together
$数组变量名=[key1 => value1, key2 => value2, ..., keyN => valueN];
Example:
<?php header("Content-type:text/html;charset=utf-8"); $arr=["color"=>"red","taste"=>"sweet","shape"=>"round","name"=>"apple"]; var_dump($arr); ?>
key can be omitted, that is, you can specify the subscript without using the =>
symbol, and the default is the index array. The default index value also starts from 0 and increases in sequence.
<?php header("Content-type:text/html;charset=utf-8"); $arr=["red","sweet","round","apple"]; var_dump($arr); ?>
Method 3: Use the array() function to initialize all elements together
$数组变量名 = array(key1 => value1, key2 => value2, ..., keyN => valueN);
The same key can be omitted, that is, If you do not use the =>
symbol to specify a subscript, it defaults to an indexed array. The default index value also starts from 0 and increases in sequence.
<?php header("Content-type:text/html;charset=utf-8"); $arr1 = array("color"=>"red","taste"=>"sweet","shape"=>"round","name"=>"apple"); var_dump($arr1); $arr2=array("red","sweet","round","apple"); var_dump($arr2); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of PHP has several array initialization methods. For more information, please follow other related articles on the PHP Chinese website!