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

How to put numbers into array in php

PHPz
Release: 2023-04-19 15:05:07
Original
689 people have browsed it

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();
Copy after login

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);
Copy after login

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

print_r($numbers);
Copy after login

Output results is:

Array
(
    [0] => 1
    [1] => 2
)
Copy after login

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

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

The output result is:

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

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);
Copy after login
The output result is:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
)
Copy after login
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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template