How to set the array in php: 1. Set the array through [array name=array('value', 'value', 'value',...);]; 2. Through [$array name[ ] = 'value';] method to set the array; 3. Through [$array name = array (numeric type key => 'value'...)] method, etc.
Recommended: "PHP Video Tutorial"
6 ways to create arrays in php
The first format
$数组名称 = array(‘值’, ‘值’, ‘值’,……);
This format does not specify the key of the element in the array. PHP will automatically create the key in the form of a number, starting from 0 and accumulating in sequence.
Format of calling array: $array name[numeric key]
<?php $arr = array('a','b','c'); echo $arr[1]; //输出b
Second format
$数组名称[] = ‘值’; $数组名称[] = ‘值’; $数组名称[] = ‘值’; ……
This format also does not specify the key of the element in the array, PHP Keys are automatically created in the form of numbers, starting from 0 and counting up.
Format of calling array: $array name[numeric key];
<?php $arr[] = 'a'; $arr[] = 'b'; $arr[] = 'c'; echo $arr[1]; //输出b
3rd format
$array name=array(numeric key=> 'Value', key of numeric type=> 'Value', key of numeric type=> 'value',...);
Calling format: $array name[key of numeric type];
<?php $arr = array(1=>'jack',2=>'lucy',500=>'hcoder'); echo $arr[500]; //输出hcoder
This format uses integers as the keys of the array. PHP's support for arrays is very flexible, and the numbers in the array can be defined arbitrarily.
If there are duplicate keys in the array, the last element will overwrite all previous keys, and the last one will be a valid value.
The 4th format
$数组名称[整数类型键] = ‘值’; $数组名称[整数类型键] = ‘值’; $数组名称[整数类型键] = ‘值’; ……
Calling format: $array name[integer type key];
<?php $arr[1] = 'jack'; $arr[2] = 'lucy'; $arr[500] = 'hcoder'; echo $arr[500]; //输出hcoder
The 5th format (associative array)
$数组名称=array(‘字符串形式的键’=>’值’,‘字符串形式的键’=>’值’,……);
Calling format: $array name['key in string form'];
<?php $arr = array('name'=>'张三', 'age'=>18); echo $arr['age']; //输出18
The 6th format (associative array)
$数组名称[ ‘字符串形式的键’]=>’值’; $数组名称[ ‘字符串形式的键’]=>’值’; ……
Calling format: $array name['string form The key'];
<?php $arr['name'] = '张三'; $arr['age'] = 18; echo $arr['age']; //输出18
The above is the detailed content of How to set an array in php. For more information, please follow other related articles on the PHP Chinese website!