Home > Article > Backend Development > How to make array keys start from 1 in php
PHP is an open source scripting language that is widely used in web development. In PHP, array is a very important data type that can be used to store a set of data. But by default, the keys of the array are arranged sequentially starting from 0. This article will introduce how to arrange the keys of the array starting from 1.
1. What is an array
According to the description of PHP official documentation, array (Array) is a very important data type in PHP. It can be used to store a group of related data items. Each data item can be a scalar (such as an integer, a floating point number, a string, etc.), an array, or even an object.
Arrays can be declared in two ways. One is using array() function and the other is using square brackets []. For example:
// 使用 array() 函数 $fruits = array("apple", "banana", "orange"); // 使用方括号 [] $fruits = ["apple", "banana", "orange"];
2. Array keys by default
In PHP, the default keys of the array are arranged sequentially starting from 0. For example, we declare an array $fruits
, which contains three elements:
$fruits = ["apple", "banana", "orange"];
Then the key-value pair of this array is as follows:
Array ( [0] => apple [1] => banana [2] => orange )
You can see , the key values of each element are 0, 1, and 2 respectively.
3. How to arrange the keys of the array starting from 1
If we need to arrange the keys of the array starting from 1, we can use PHP's built-in functionarray_combine()
. This function merges two arrays into an associative array, with the values in the first array as keys and the values in the second array as keys.
Therefore, we can first use the range()
function to generate a continuous numerical array and use it as the key name (provided that the number of elements in the array matches the corresponding key name equal numbers), and then use the array_combine()
function to combine the key array and the value array into an associative array.
The sample code is as follows:
// 声明一个数组 $fruits $fruits = ["apple", "banana", "orange"]; // 使用 range() 函数生成键名数组 $keys = range(1, count($fruits)); // 使用 array_combine() 函数将两个数组组合成一个关联数组 $result = array_combine($keys, $fruits); // 输出新数组 print_r($result);
Execute the above code and you will get the following output:
Array ( [1] => apple [2] => banana [3] => orange )
4. Conclusion
This article introduces how to make PHP array keys are sorted starting from 1. We can easily achieve this by using the range()
and array_combine()
functions. Of course, in actual development, we should choose the most suitable solution according to the specific situation.
The above is the detailed content of How to make array keys start from 1 in php. For more information, please follow other related articles on the PHP Chinese website!