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);
This code will output the following result:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
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);
This code will output the following result:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
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);
This code will output the following result:
Array ( [0] => 123 [1] => 456 [2] => 789 )
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!