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

How to convert numbers into array in php

PHPz
PHPzOriginal
2023-04-26 14:21:59773browse

In programming, sometimes we need to convert a number into an array form. At this time, we can use PHP's own function to achieve this. This article will introduce several commonly used methods.

1. Use the str_split function

The str_split function can split a string into several elements according to the specified length and return an array. If we want to convert a number into an array, we can first use the intval function to convert it into a string form, and then use the str_split function to split it.

Sample code:

$num = 123456;
$str = (string)$num;
$arr = str_split($str);
print_r($arr);

Output result:

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

2. Use the preg_split function

The preg_split function can split a string according to the specified regular expression. and returns an array. If we want to convert a number into an array, we can convert it into string form and then use the preg_split function to split it.

Sample code:

$num = 123456;
$str = (string)$num;
$arr = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($arr);

Output result:

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

3. Use str_split and array_map functions

Use str_split function to convert numbers into string form Finally, use the array_map function to convert each element into an integer, and you will get an array composed of numbers.

Sample code:

$num = 123456;
$str = (string)$num;
$arr = array_map('intval', str_split($str));
print_r($arr);

Output result:

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

Summary:

In PHP, you can use the str_split and preg_split functions to convert numbers into arrays. You can also use the array_map function to perform integer conversion, and just choose the method that suits you.

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