Home >Backend Development >PHP Tutorial >How to define arrays in php
There are four ways to define arrays in PHP: square brackets define numeric or string arrays. The array keyword defines an associative array. Short array syntax (PHP 5.4) defines simple arrays of numbers or strings. The array() function defines an empty array or an initial array.
Methods of defining arrays in PHP
In PHP, there are several ways to define arrays:
1. Use square brackets ([])
The most common method is to use square brackets:
<code class="php">$array = array(1, 2, 3); // 定义一个由数字组成的数组</code>
2. Use the keyword array
You can also use the array keyword to define an array:
<code class="php">$array = array( 'a' => 1, 'b' => 2, 'c' => 3 ); // 定义一个由键值对组成的关联数组</code>
3. Use short array syntax (PHP 5.4)
For simplicity For a one-dimensional array, you can use short array syntax:
<code class="php">$array = [1, 2, 3];</code>
4. Use the built-in function array()
You can also use the array() function to define an array:
<code class="php">$array = array(); // 定义一个空数组 $array = array(1, 2, 3); // 定义一个由数字组成的数组</code>
Which method to choose
Which method to choose depends on the type and complexity of the array:
The above is the detailed content of How to define arrays in php. For more information, please follow other related articles on the PHP Chinese website!