【问题标题】:How do I explode an integer如何分解一个整数
【发布时间】:2011-06-19 15:02:57
【问题描述】:

这个问题的答案可能很简单。但我对编程很陌生。所以要温柔...

我正在努力为您的一位客户进行快速修复。我想得到一个整数的总位数,然后分解这个整数:

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。

基本上:如何在没有分隔符的情况下分解整数,以及如何找到整数中的位数。

【问题讨论】:

    标签: php arrays integer delimiter explode


    【解决方案1】:

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

    【讨论】:

    • 您也可以在 $array 上使用sizeof()(又名count())来获取位数。
    • 太棒了。多谢你们。最重要的是我得到了sizeof/count的位数,然后根据位数的总和将整数重建为更小的整数。我必须将 $rx_freq 分成两块。兆赫兹和千赫兹。有时 MHz 是 4 位数,有时是 3 位数。
    【解决方案2】:

    使用str_split()函数:

    $array = str_split(1331000000);
    

    由于 PHP 的自动类型强制,传递的 int 将自动转换为字符串。但是,如果您愿意,也可以添加显式演员表。

    【讨论】:

    • 您将如何准确地为此添加显式转换?
    • str_split((string)$number);
    • 你评论 > 对我很有帮助,我想知道为什么当您将整数传递给 str_split 时,它也可以使用字符串。
    【解决方案3】:

    我知道这是旧的,但只是偶然发现它。也许它可以帮助别人。

    首先将数字转换为字符串。这很容易做到。 $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)
    

    希望这对某人有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-13
      • 2018-12-03
      相关资源
      最近更新 更多