php 如何在PHP中将整数转换为数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8118964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:59:39  来源:igfitidea点击:

How to convert an integer to an array in PHP?

phparrays

提问by rob.s

What would be the most simple way to convert an integer to an array of numbers?

将整数转换为数字数组的最简单方法是什么?

Example:

例子:

2468should result in array(2,4,6,8).

2468应该导致array(2,4,6,8).

回答by Berry Langerak

You can use str_splitand intval:

您可以使用str_splitintval

$number = 2468;

    $array  = array_map('intval', str_split($number));

var_dump($array);

Which will give the following output:

这将给出以下输出:

array(4) {
  [0] => int(2)
  [1] => int(4)
  [2] => int(6)
  [3] => int(8)
}

Demo

演示

回答by 4DA

You can cut-off the last digit by taking the number modulo 10.

您可以通过对数字取模 10 来截断最后一位数字。

Don't tell it to anyone!

不要告诉任何人!

do 
{
    $array.add(num % 10);
    num = num / 10;
}
while (num != 0);

回答by Nathan Q

use str_split() function

使用 str_split() 函数

$array = str_split($str);

http://php.net/manual/en/function.str-split.php

http://php.net/manual/en/function.str-split.php

回答by breiti

Example #2 Splitting a string into component characters

Example #2 将字符串拆分为组成字符

$str = 'string';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);