2017-11-04 112 views
0

這是一個瘋狂的...

我有一個來自$ _GET請求的var。它回聲良好,但無論我做什麼,我都無法將它傳遞給一個函數,而無需對該值進行硬編碼。

$txAmount = strip_tags($_GET['amt']); 

相呼應$ txAmount返回如下:23.28684804(因爲它應該)

// Running some validation to ensure it's only digits and a period 
if(preg_match_all('/^[0-9,.]*$/', $txAmount) && strpos($txAmount, '.') !== false) { 

// then some other functions run, nothing that uses or affects $txAmount 

// Then I call a class to run the function, all other variables being passed in are working fine 
$findTX = $client->findTx($payment_address, $txAmount, $listTransactions); 

// This is the function 
function findTx($address, $txAmount, $array) 
    { 
     foreach ($array as $key => $val) { 
      if ($val['address'] === $address && $val['amount'] === $txAmount) { 

       return $val['txid']; 
      } 
     } 
     return null; 
    } 

而這正是它去山雀起來......

它只是拒絕匹配$ txAmount到$ val ['amount'],儘管它們完全相同,應該返回true。

我可以使它發揮作用的唯一途徑是通過硬編碼(在腳本其他地方)的值所有這些都將工作得很好:

$txAmount = 23.28684804; 

$findTX = $client->findTx($payment_address, 23.28684804, $listTransactions); 

if ($val['address'] === $address && $val['amount'] === 23.28684804) 

我甚至嘗試了微調可變只是情況下有一些隱藏的空白有,但仍然沒有喜悅:

$txAmount = trim($txAmount); 

我是不是要瘋了這裏還是有一些瘋狂的怪癖其中PHP只是討厭這個變量?可能與小數點後8位有什麼關係?

+1

嘗試打印使用'的var_dump($ txAmount)'變量。也許這是一個對象?如果是這樣,嘗試將其轉換爲浮動? (例如'floatval($ txAmount)== floatval($ val ['amount'])' –

+0

啊,我們正在某處......它傾倒了字符串(11)「23.28684804」'但在我要搜索的數組中它被標記爲'float(23.28684804)'。我怎樣才能改變$ txAmount的格式來使它工作? – user3717922

+0

使用'floatval'。我給出了上面的例子。 –

回答

0

簡單的回答,在findTx函數if條件下,用$val['amount'] == $txAmount代替$val['amount'] === $txAmount

原因:在PHP中,===要求比較的兩個值屬於同一類型,而==將嘗試忽略類型差異。您可以使用gettype()來檢查txAmount$val['amount']的類型。當$txAmount來自$_GET時,類型可能有所不同,並且與===進行比較將要求您找到一種將它們轉換爲相同類型的方法 - 如註釋中所示或使用類型轉換運算符(例如$txAmount = (float) $txAmount等)。

但是,使用==,PHP將理解正在比較的內容,並且在此情況下從=====的更改將比處理使用不同數據類型的細節更容易,因爲這只是一個比較操作這不會以任何方式改變數據。

您可能會發現在PHP數據類型雜耍有趣以下參考:http://php.net/manual/en/language.types.type-juggling.php