2017-11-04 94 views
0

我試圖subtrat與數字結果輸出subtrating結果當我歌廳未知的結果結果例子555555而不是5這裏是我的代碼:UNKNOW輸出,數字

<?php 
$txt = "12345678910"; 
$nu = 2; 
$u = 8; 
$disp = str_split($txt, $nu); 
for($i = 0; $i < $u; $i++) { 
    $count += count($disp[$i]); 
    if(strlen($disp[$i]) != $nu) 
    { 
     $count = substr($count, 0, 1); 
     $uu = ($count - 1); 
     $we =substr($uu, 0, 1); 
     echo $we; 
    } 
} 
?> 

感謝您的閱讀和影響我的解決辦法

+0

我只想得到單個結果示例5而不是55555 –

回答

0

這是在回答您刪除錯誤,所以它只是顯示5.

我認真沒有理解對你的意圖與此代碼,但擺脫你的錯誤,你需要重構的東西。

您的值$u取決於$txt的長度以及您在str_split中設置的位數。 $ u的值太大,因爲索引6和7的條目不存在於您的數組中。

1日去...

<?php  
$txt = "12345678910"; // The string of digits 

$nu = 2;    // How many digits per array 
$disp = str_split($txt, $nu); // The array of strings of $nu digits 
$u = count($disp); // Calculate the size of $disp - don't guess 

$count = 0; // initialise the variable 

for ($i = 0; $i < $u; $i++) { 
    $count += count($disp[$i]); // count($disp[$i]) will always be 1       
    // Looking for an entry that isn't $nu digits in size 
    if (strlen($disp[$i]) != $nu) {      
     $count = substr($count, 0, 1); // Rip off the 1st digit of the index count 
     $uu = ($count - 1); // decrement it? 
     echo $uu; // display it 
    } 
} 

另一種方式...... 因此,使用的foreach是更好,因爲它需要的所有的辛勤工作照顧。

<?php 
$txt = "12345678910"; 
$nu = 2; 

$disp = str_split($txt, $nu); 
// DEBUG 
var_dump($disp); 

$count = 0; // Initialise the variable before we can += it 
foreach ($disp as $number) { 
    $count += 1; 
    if (strlen($number) != $nu) { 
     // Taking the index count, getting the 1st digit 
     $count = substr($count, 0, 1); 
     // Then subtracting 1 from it 
     $uu = $count - 1; 
     echo $uu; 
    } 
} 

所以這只是解決你有什麼,所以它有點更好,沒有錯誤只。

在PHP中,從字符串到整數並且再次返回時,盲目類型化可能是一個陷阱。