In PHP, use the array() function to initialize an array. The syntax format is as follows:
$array_name = array(value1, value2, ..., valueN);
Among them, $array_name is the array name, and value1 to valueN are optional array elements. For example, the following code demonstrates how to use the array() function to initialize an array containing three elements:
$fruits = array("apple", "banana", "orange");
In addition, the array() function also supports the following ways to initialize the array:
Use key => ; The form of value, that is, the subscript and value of the array element are separated by "=>", as shown below:
$array_name = array(key1 => value1, key2 => value2, ..., keyN => valueN);
For example, the following is an example of using key => value to initialize an array:
$scores = array("Math" => 90, "English" => 80, "Chinese" => 95);
In addition, you can also use the range() function to generate integers or characters within a certain range and use them as array elements. The syntax format of the range() function is as follows:
array range ( mixed $start , mixed $end [, number $step = 1 ] )
Among them, $start and $end are the start and end values of the range, and $step is an optional parameter, indicating the step, that is, the interval for increasing the value. For example, the following code uses the range() function to generate integers from 1 to 5 and stores them in the array $numbers:
$numbers = range(1, 5);
Finally, one thing to note is that the subscripts of PHP arrays do not necessarily start from 0 , it is not necessary to only use numbers as subscripts, you can also use strings, Boolean, floating point and other types as subscripts. Therefore, when initializing an array, you can flexibly use various types of data as array subscripts.
The above is the detailed content of How to initialize an array with new in php. For more information, please follow other related articles on the PHP Chinese website!