Home > Article > Backend Development > PHP array subscript starts from
In the PHP programming language, the subscripts of arrays start from 0. This means that the first element of the array has index 0, the second element has index 1, and so on. This subscripting method is widely used in many programming languages, including JavaScript and C.
In PHP, when using an array, the way to declare and initialize the array is as follows:
// 声明一个空数组 $array = array(); // 声明并初始化一个数组 $array = array('apple', 'banana', 'orange'); // 访问数组元素 echo $array[0]; // 输出: apple echo $array[1]; // 输出: banana echo $array[2]; // 输出: orange
As you can see, you can access the i-th element in the array using $array[i] . The value of i starts from 0 and ends with the number of elements in the array minus 1.
In PHP, you can also use associative arrays. An associative array is an array of key-value pairs, where each key is associated with a unique string. The declaration and access of an associative array are as follows:
// 声明并初始化一个关联数组 $fruit = array('apple' => 1, 'banana' => 2, 'orange' => 3); // 访问关联数组元素 echo $fruit['apple']; // 输出: 1 echo $fruit['banana']; // 输出: 2 echo $fruit['orange']; // 输出: 3
In an associative array, the value of the key represents the index position in the array. Unlike ordinary array subscripts, the key value of an associative array can be any string, not just a numerical value.
In general, it is a very common practice to use array subscripts starting from 0 in PHP. If there is no special need, it is best to follow this standard to maintain code consistency and readability.
The above is the detailed content of PHP array subscript starts from. For more information, please follow other related articles on the PHP Chinese website!