如何将整数拆分为单个数字

26

这个问题的答案可能很简单,但我对编程非常陌生。所以请温柔一点......

我在工作中试图为客户快速修复一个问题。我想获取一个整数中数字的总数,并将该整数拆分:

rx_freq = 1331000000 ( = 10 )
  $array[0] = 1
  $array[1] = 3
  .
  .
  $array[9] = 0

rx_freq = 990909099 ( = 9 )
  $array[0] = 9
  $array[1] = 9
  .
  .
  $array[8] = 9

我无法使用 explode 函数,因为该函数需要一个分隔符。我已经在 Google 和 Stackoverflow 上进行了搜索。

基本上:如何在没有分隔符的情况下使用 explode 函数,以及如何找出一个整数中的数字个数。

3个回答

50

$array = str_split($int)$num_digits = strlen($int) 应该可以正常工作。


2
你也可以在 $array 上使用 sizeof()(又称为 count())来获取数字的数量。 - ThiefMaster
太好了。谢谢大家。最重要的是,我要获得数字的 sizeof/count,并根据数字总和重新构建整数到更小的整数中。我必须将 $rx_freq 分成两个块。 MHz 和 KHz。有时 MHz 是 4 位数字,有时是 3 位数字。 - chriscandy

15

使用str_split()函数:

$array = str_split(1331000000);

由于PHP具有自动类型转换功能,传递的整数将自动转换为字符串。但如果您希望,也可以添加显式转换。


你会如何在这里添加一个显式类型转换? - Scott
3
将变量$number转换为字符串后,使用str_split函数对其进行分割。 - ThiefMaster
你的注释:<<由于 PHP 的自动类型转换,传递的整数将自动转换为字符串。>> 对我非常有帮助,我很好奇传递整数给 str_split 函数(该函数接受字符串作为参数)时为什么也能正常工作。 - Holy semicolon

1
我知道这篇文章有点旧了,但我刚看到它。也许它能帮助其他人。
首先将数字转换为字符串非常容易。 $number = 45675; //你想要拆分的数字
$nums = ""; //Declare a variable with empty set.

$nums .= $number; //concatenate the empty string with the integer $number You can also use

$nums = $nums.$number; // this and the expression above do the same thing choose whichever you
                     //like.. This concatenation automatically converts integer to string
$nums[0] is now 4, $nums[1] is now 5, etc..
$length = strlen($nums); // This is the length of your integer.
$target = strlen($nums) -1; // target the last digit in the string;    
$last_digit = $nums[$target]; // This is the value of 5. Last digit in the (now string)

希望这能帮助到某个人!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接