2017-04-18 60 views
0

好吧,我覺得這很奇怪,但應該有一個解釋。這是發生了什麼。意外的PHP數組關鍵行爲

這裏該代碼應該沒有什麼呼應:

$str = '[email protected]'; 
$key = '11111'; 
echo strpos($str, $key); 
exit; 

..是的,這正是我所得到的,什麼都沒有。但是! 如果我使用$鍵(其中包含字符串)作爲陣列的實際鑰匙:

$str = '[email protected]'; 
$arr = array('11111' => 'test'); 
foreach ($arr as $key => $val) 
{ 
    echo 'String: '.$str.'<br>'; 
    echo 'Key: '.$key.'<br>'; 
    echo 'Found at position: '.strpos($str, $key); 
} 
exit; 

我得到這個驚人的,不可思議的結果:

String: [email protected] 
Key: 11111 
Found at position: 2 

那麼PHP在這裏找到被串​​是信g 但是,什麼是更驚人的,是的位數改變了結果:

$str = '[email protected]'; 
$arr = array('111' => 'test'); 
foreach ($arr as $key => $val) 
{ 
    echo 'String: '.$str.'<br>'; 
    echo 'Key: '.$key.'<br>'; 
    echo 'Found at position: '.strpos($str, $key); 
} 
exit; 

這一給出:

String: [email protected] 
Key: 111 
Found at position: 9 

在這方面的專家? 謝謝。

編輯: 這是在我的項目中使用的實際代碼例子給出了這樣的誤報:

$email = '[the email of the user here]'; 
$arr = array(
    // [...] 
    '11111' => 'Banned', 
    '22222' => 'Banned', 
    '33333' => 'Banned', 
    // [...] 
); 
foreach ($arr as $key => $reason) 
{ 
    if (strpos($email, (string)$key) !== false) 
    { 
     return 'Keyword: '.(string)$key.' found in the user Email address with reason: '.(string)$reason; 
    } 
} 

因此,即使用(string)在變量$key前它在登錄表單

禁止無辜
+0

[與Strpos在PHP的問題(的可能的複製https://stackoverflow.com/questions/1039738/問題與strpos在PHP) – mickmackusa

回答

1

使用它,它會正常工作。我輸入$keystring。 PHP函數strpos用於匹配字符串中的子字符串,而不是整數值。如果你看看文檔,清楚地提到

第二個參數:If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

<?php 
ini_set('display_errors', 1); 
$str = '[email protected]'; 
$arr = array('11111' => 'test'); 
foreach ($arr as $key => $val) 
{ 
    echo 'String: '.$str.'<br>'; 
    echo 'Key: '.$key.'<br>'; 
    echo 'Found at position: '.strpos($str, (string)$key); 
} 
+0

感謝您的答案,以及這正是我在我的項目的代碼循環做的,但它仍然打這個誤報。所以問題是,爲什麼在'$ key'之前沒有或甚至沒有(字符串)發生?這很有趣 ! – durduvakis

+0

@durduvakis請檢查我的當前代碼,如果它仍然無法正常工作,請在您的帖子中分享該代碼無法使用。 –

+0

如果您發現它是一個字符串,只要它在單引號中。 – durduvakis