Home >Backend Development >PHP Problem >There are several types of PHP array definitions
1. array() function
1.1 No key value
$arr=array(1,2,3,4);
1.2 Key-value pair
$arr=array( 'name'=>'myj', 'age'=>'18', 'phone'=>'1888888888' );
1.3 Empty array
$arr=array();
2. compact() function
The compact function can convert variables into arrays.
$a = 'aaa'; $b = 'bbb'; $c = 'ccc'; $arr3 = compact('a','b','c');
Output:
{"a":"aaa","b":"bbb","c":"ccc"}
3. array_combine() function
array_combine() function can combine two arrays into a new array, where One of the arrays is the key name, and the value of the other array is the key value.
$arr_key = array('a','b','c','d'); $arr_val = array('1','2','3','4'); echo var_dump(array_combine($arr_key,$arr_val));
Output:
'a' => string '1' (length=1) 'b' => string '2' (length=1) 'c' => string '3' (length=1) 'd' => string '4' (length=1)
4. Use the array_fill() function to create an array
The array_fill() function fills the array with a given value class
Definition format:
array_fill(start,number,value)
start: starting index
number: number of arrays
value: array value
Example:
$a=array_fill(2,3,"Dog"); print_r($a);
Output result:
Array ( [2] => Dog [3] => Dog [4] => Dog )
5. Range() function
Definition format:
array range(first,second,step)
first: minimum value of element
second: maximum element value
step: element step size (default 1)
$arr = range(1,5); 输出:[1,2,3,4,5] $arr = range(1,15,3); 输出:1,4,7,10,13
Recommended tutorial: PHP video tutorial
The above is the detailed content of There are several types of PHP array definitions. For more information, please follow other related articles on the PHP Chinese website!