In PHP, sometimes you need to convert a number into an element in an array. This can be achieved through some built-in PHP functions such as str_split()
, explode()
and preg_split()
.
Use the str_split()
str_split()
function to split the string into a character array. Because numbers can also be viewed as strings, you can use this function to convert a number into an array.
$num = 12345; $arr = str_split($num); print_r($arr);
The output will be:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
Use the explode()
explode()
function to expand the string as specified separator and store the result in an array.
$num = "1,2,3,4,5"; $arr = explode(",", $num); print_r($arr);
The output will be:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
Use preg_split()
##preg_split() function with
explode( ) function is similar, but regular expressions can be used for segmentation.
$num = "1+2-3*4/5"; $arr = preg_split("/[-+\/*]/", $num); print_r($arr);
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
/[- \/*]/ to specify the delimiter. This regular expression will match a set of possible delimiters:
-,
,
*, and
/.
The above is the detailed content of How to convert a number into an element in an array in php. For more information, please follow other related articles on the PHP Chinese website!