In PHP and other program language programming, the creation of arrays is often used, in front-end development, JS array creation can be created and assigned directly by [] and new Array (). But what are the methods of creating arrays in PHP? After reviewing the information and collecting the online collection summarized below:
1. Creating an array with array is the most common and convenient way to do this:
$arr = Array (' A ', ' B ', ' C '); $arr [] = ' a '; $arr [] = ' B '; $arr [] = ' C '; $arr = Array (' name ' = ' Guan Yu ', ' age ' = ', ' sex ' = ' male ');
2. Sometimes it is necessary to create a random array of Len length, so you can use range ():
Definition: Array range (FIRST,SECOND,STEP)//first: element minimum Second: element max step: Element Step (amount to increase)
$number = range (0,5); Print_r ($number); Print: Array ([0] = 0 [1] = 1 [2] = 2 [3] = 3 [4] = 4 [5] = 5) $number = range (0,50,10); Print_r ($number); Print: Array ([0] = 0 [1] = [2] = [3] = + [4] = [5] = +) $letter = Range ("A", "D"); Print_r ($letter); Print: Array ([0] = a [1] = b [2] = = c [3] = + D)
3. Of course, under certain specific requirements, some variables need to be stored in an array, the variable names of those variables are converted to key names, and the values of the variables are converted to key values (provided that the variable exists):
$firstname = "Peter"; $lastname = "Griffin"; $age = "38"; $result = Compact ("FirstName", "LastName", "age"); Print_r ($result); Print: Array ([FirstName] + peter [LastName] = Griffin [age] = "$firstname =" Peter "; $lastname = "Griffin"; $age = "38"; $name = Array ("FirstName", "LastName"); $result = Compact ($name, "location", "age"); Print_r ($result); Print: Array ([FirstName] = Peter [LastName] = Griffin [age] + 38)///Because the $location variable does not exist, it cannot be stored in the array
4. Merge two arrays into a new array, the value of the first array is the key name of the new array, and the value inside the second array is the key value of the new array:
Definition: the Array_combine () function can combine two arrays into a new array, one of which is the key name and the other is the value of the key.
$a 1=array ("a", "B", "C", "D"); $a 2=array ("Cat", "Dog", "Horse", "Cow"); Print_r (Array_combine ($a 1, $a 2)); Print: Array ([a] = Cat [b] = Dog [c] = = Horse [d] = Cow)
5. Create a fixed-length array like a key value:
Definition: Array_fill (start,number,value)//start: Starting index number: Value: Array value
$a =array_fill (2,3, "Dog"); Print_r ($a); Print: Array ([2] = dog [3] = dog [4] = dog)