In PHP, we can use arrays to store and process large amounts of data. Putting numbers into an array is also a very basic operation. Here are some methods you can use:
In PHP, we can use "[]" syntax to put numbers into an array. This syntax is very simple and practical. The following is an example:
$arr = []; // 创建一个空数组 $arr[] = 1; // 将数1放进数组中 $arr[] = 2; // 将数2放进数组中 $arr[] = 3; // 将数3放进数组中 print_r($arr); // 输出数组的内容
The above code will output the following results:
Array ( [0] => 1 [1] => 2 [2] => 3 )
We can see that using the "[]" syntax can easily put numbers into an array , and this syntax is very simple.
In PHP, we can also use the "array_push()" function to put numbers into an array. This function adds one or more numbers to the end of an array. The following is an example:
$arr = []; // 创建一个空数组 array_push($arr, 1); // 将数1放进数组中 array_push($arr, 2); // 将数2放进数组中 array_push($arr, 3); // 将数3放进数组中 print_r($arr); // 输出数组的内容
The above code will output the following results:
Array ( [0] => 1 [1] => 2 [2] => 3 )
We can see that using the "array_push()" function can also easily put numbers into an array , and this function is very simple.
In PHP, we can also use the "array_unshift()" function to put numbers into an array. This function adds one or more numbers to the beginning of an array. The following is an example:
$arr = []; // 创建一个空数组 array_unshift($arr, 3); // 将数3放进数组中 array_unshift($arr, 2); // 将数2放进数组中 array_unshift($arr, 1); // 将数1放进数组中 print_r($arr); // 输出数组的内容
The above code will output the following results:
Array ( [0] => 1 [1] => 2 [2] => 3 )
We can see that using the "array_unshift()" function can also easily put numbers into an array , and this function is very practical. It allows us to add numbers at the beginning of the array instead of only at the end.
To sum up, you can easily put numbers into an array using the above three methods. These methods are very simple and practical, and can make us more convenient when processing data. Using arrays allows us to better store and process data, so learning how to put numbers into arrays is also a very important skill.
The above is the detailed content of How to put numbers into array in php. For more information, please follow other related articles on the PHP Chinese website!