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

How to put string numbers into array in php

PHPz
Release: 2023-04-20 09:19:51
Original
1254 people have browsed it

In PHP, it is not difficult to put string numbers into an array. This article will introduce you how to use PHP array functions to convert string numbers into arrays.

First, we need to use PHP’s built-in string function explode(). The explode() function explodes a string into an array. For example, we can decompose the following string into an array:

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

This code will output the following result:

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

Now, the $array variable is an array containing the string numbers.

We can also use another built-in function of PHP, str_split(). The str_split() function splits a string into individual characters and stores them in an array. For example, we can decompose the following string into an array:

$num_str = '12345';
$array = str_split($num_str);
print_r($array);
Copy after login

This code will output the following result:

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

Now, the $array variable is an array containing the string numbers.

Finally, we can also use the PHP function preg_split(). The preg_split() function splits a string into an array based on a regular expression. For example, we can decompose the following string into an array:

$num_str = '123-456-789';
$array = preg_split('/-/', $num_str);
print_r($array);
Copy after login

This code will output the following result:

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

Now, the $array variable is an array containing the string numbers.

Familiar with these functions, we can easily convert string numbers into arrays. Hope this article can be helpful to you!

The above is the detailed content of How to put string 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