Home>Article>Backend Development> What are the two ways to define arrays in php?
Two methods: 1. Directly assign values to array elements. The syntax is "$array variable name [subscript] = value;". The "subscript" can be a string, an integer, or is empty; 2. Use the array() function to create an array, with the syntax "$array variable name = array(key 1 = > value 1, key 2 = > value 2,...);".
The operating environment of this tutorial: Windows 7 system, PHP version 7.1, DELL G3 computer
Defining arrays in PHP is very flexible, unlike other Unlike arrays in many programming languages, PHP does not need to specify the size of the array when creating it, or even declare it before using it. It can also store any type of data in the same array.
PHP can use the following two methods to define an array:
Directly assign values to array elements
Use the array() function
We will introduce these two methods in detail with our actual code examples below.
1. Directly assign values to array elements
We can use the form "$Array variable name [subscript] = value ;
" format to create and initialize the array
The subscript
can be a string, an integer, or empty (that is, no specific index value is specified).
Example 1:
Output result:
Example 2:
Output result:
It can be seen that when we do not specify a specific index value within square brackets, the default is a numeric index, and the index value increases sequentially starting from 0 by default.
Tip: In addition to using the var_dump() function to print the entire array, you can also use the print_r() function.
There is no size limit for arrays in PHP, so in the above array, you can continue to add new elements to the array in the same way. When accessing the elements in the array, you can use "$array variable name [subscript]". The sample code is as follows:
'; echo '$array[1] = '.$array[1].'
'; echo '$array[2] = '.$array[2].'
'; echo '$array[3] = '.$array['url'].'
'; ?>
2. Use array() function
Another way to define an array is to use the array() function to create a new array. It accepts a certain number of key=>value parameter pairs separated by commas. The syntax format is as follows:
$数组变量名 = array(key1 => value1, key2 => value2, ..., keyN => valueN);
1) Direct array() function, without adding any parameters, can create an empty array
Output:
2) If you do not use the => symbol to specify a subscript, it defaults to an index array. The default index value also starts from 0 and increases in sequence.
Output:
3) The array() function also accepts a certain number ofkey=>value# separated by commas ##Parameter pair, this definition is an associative array.
"欢迎来到",1=>"php中文网",2=>"PHP教程","URL"=>"//m.sbmmt.com/"); //输出语句 var_dump($array); ?>Output result:
PHP Video Tutorial"
The above is the detailed content of What are the two ways to define arrays in php?. For more information, please follow other related articles on the PHP Chinese website!