2011-02-01 21 views
14

答案可能很簡單。但我對編程非常新鮮。所以要溫柔...如何分解整數

我在努力爲您的客戶做一個快速修復。我想要得到的數字總數的整數,然後爆炸的整數

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 

我不能使用爆炸,因爲這需要功能的分隔符。我搜索了Google和Stackoverflow。

基本上:我如何分解沒有分隔符的整數,以及如何找到整數中的數字位數。

回答

31

$array = str_split($int)$num_digits = strlen($int)應該工作得很好。

+2

您還可以在$ array上使用`sizeof()`(又名`count()`)來獲取位數。 – ThiefMaster 2011-02-01 22:59:15

+0

太好了。多謝你們。最重要的是我得到了數字的大小/數量,然後根據數字的總和將整數重建爲較小的整數。我必須將$ rx_freq分成兩個塊。 MHz和KHz。有時候MHz是4 digtis,有時是3位數字。 – chriscandy 2011-02-01 23:06:34

8

使用str_split()功能:

$array = str_split(1331000000); 

由於PHP的自動類型強制傳遞的INT將自動轉換爲字符串。但如果你想要的話,你也可以添加一個明確的演員。

2

我知道這是舊的,但只是碰到它。也許它可以幫助別人。

首先將數字轉換爲字符串。這很容易做到。 $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) 

希望這可以幫助別人!