Home  >  Article  >  Backend Development  >  How to put numbers into array in php

How to put numbers into array in php

PHPz
PHPzOriginal
2023-04-19 14:11:02639browse

PHP is a scripting language widely used in web development. It is very flexible and easy to learn and use. In PHP, putting numbers into arrays is a common operation. The following will introduce how to use PHP to put numbers into an array.

It is very common to use arrays in PHP. You can create an array in the following ways:

$numbers = array();

Now, we can use the array_push() function to put the number into in this array. For example, we can put the value 1 and the value 2 into the array:

array_push($numbers, 1, 2);

Use the print_r() function to view the contents of the array:

print_r($numbers);

Output results is:

Array
(
    [0] => 1
    [1] => 2
)

We can also use the following method to directly create an array of numbers:

$numbers = array(1, 2, 3, 4, 5);
print_r($numbers);

The output result is:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

In addition to using the array function, we can also use ## The #[] symbol adds a value to the array:

$numbers[] = 6;
$numbers[] = 7;
print_r($numbers);
The output result is:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
)
It should be noted that when using the

[] symbol to add elements , if no subscript is specified, PHP will automatically assign the subscript according to the largest integer key in the current array plus 1.

Summary

Putting values ​​into an array is a basic operation in PHP programming. You can use array functions or the

[] symbol to add new elements. It is important to note that PHP automatically assigns subscripts to added elements, especially when no subscripts are specified.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn