2009-11-16 42 views
1

我目前通過O'Reilly的「PHP編程」的工作和所遇到的這臺名爲「比較類型的比較操作執行」:PHP比較運營商和數據類型

 
First Operand    | Second Operand    | Comparison 
----------------------------------------------------------------------- 
Number      | Number      | Numeric 
String that is numeric  | String that is numeric  | Numeric 
String that is numeric  | Number      | Numeric 
String that is not numeric | Number      | Lexicographic 
String that is numeric  | String that is not numeric | Lexicographic 
String that is not numeric | String that is not numeric | Lexicographic 

我的規則當且僅當至少一個操作數是一個數字或兩個操作數都是數字串時,執行哪種比較類型的拇指纔是「數字」。這似乎得到php.net page on Comparison Operators的支持,其中指出:「如果您將整數與字符串進行比較,則該字符串將轉換爲數字,如果比較兩個數字字符串,則將它們作爲整數進行比較。」

但是,這意味着表格第四行中的比較應該是「數字」。表中是否包含錯誤,或者我的規則錯誤?

+0

你的規則是錯誤的。嘗試比較''字符串「== 0'和'intval(」string「)== 0' – 2009-11-16 05:30:11

+0

@Ast Derek:兩個比較的結果似乎都是真的。 – user200783 2009-11-16 06:08:26

回答

2

Editted:一個完整​​的基於評論的臉。

你的摘要是正確的,表是錯誤的。如果一個操作數是數字,則會在字符串開頭的數字位上嘗試進行轉換。如果沒有數字引導器,轉換將返回零。轉換髮生在小數和計算的合理結果上,而不僅僅是整數。

下面的代碼演示了行爲

 

if (2 > '10 little pigs') 
     print 'Integer does not coerce string'."\n"; 
else 
     print 'Integer does coerce string'."\n"; 

if (2.5 > '10 little pigs') 
     print 'Decimal does not coerce string'."\n"; 
else 
     print 'Decimal does coerce string'."\n"; 

if (5/3 > '2 little pigs') 
     print 'Rational result does not coerce string'."\n"; 
else 
     print 'Rational result does coerce string'."\n"; 

if (0 == 'No little pigs') 
     print 'Non numeric coerced to zero'."\n"; 
else 
     print 'Non numeric not coerced'."\n"; 

if (-0.156 > '-127 is a minumum value of a signed 8 bit number') 
     print 'Negative decimal does coerce string'."\n"; 
else 
     print 'Negative decimal does not coerce string'."\n"; 

if ('-0.156' > '-127') 
     print 'Both are converted if all numeric'."\n"; 
else 
     print 'No conversion if both are all numeric'."\n"; 

if ('-0.156' > '-127 is a minumum value of a signed 8 bit number') 
     print 'Successful conversion of one does coerce the other'."\n"; 
else 
     print 'Successful conversion of one does not coerce the other'."\n"; 
 
+0

php.net語句顯示「如果您將整數與字符串進行比較,則字符串將轉換爲數字。」這是否意味着整數與字符串(任何字符串,數字或非數字)的比較是數字?這不符合你的「翻譯」。 – user200783 2009-11-16 06:11:50

+0

重新閱讀php.net頁面似乎在您引用的表格和該頁面之間的術語中不匹配。這似乎並不是所有的數字行爲都相同。我正在嘗試爲該案例提供一段演示代碼。 – Bell 2009-11-16 06:48:15