How to initialize an array with new in php

WBOY
Release: 2023-05-19 15:37:39
Original
527 people have browsed it

In PHP, use the array() function to initialize an array. The syntax format is as follows:

$array_name = array(value1, value2, ..., valueN);
Copy after login

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");
Copy after login

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);
Copy after login

For example, the following is an example of using key => value to initialize an array:

$scores = array("Math" => 90, "English" => 80, "Chinese" => 95);
Copy after login

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 ] )
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!