2017-04-18 130 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