dongzhi9192 2017-04-18 04:04
浏览 15
已采纳

意外的PHP数组键行为

Ok I find this very weird but there should be an explanation. Here is what happens.

This code here should echo nothing:

$str = 'a@gmail.com';
$key = '11111';
echo strpos($str, $key);
exit;

.. and yes this is exactly what I get, nothing. But !! If I am to use the $key (which contains a string) as an actual key of an array:

$str = 'a@gmail.com';
$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;

I get this amazing, magical result:

String: a@gmail.com
Key: 11111
Found at position: 2

So what php found here was the string 11111 to be the letter g But what is even more amazing, is that the number of digits changes the result:

$str = 'a@gmail.com';
$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;

This one gives:

String: a@gmail.com
Key: 111
Found at position: 9

Any experts on this ? Thank you.

EDIT: This is actual code example used in my project which gives such false positives:

$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;
    }
}

So even using the (string) in front of the variable $key it bans innocents at the login form

  • 写回答

1条回答 默认 最新

  • douxia2053 2017-04-18 04:07
    关注

    use this, It will work fine. I type casted $key into string. PHP function strpos for matching substring with in the string, not the integer value. If you look into the documentation, it is clearly mentioned

    Second parameter: 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 = 'a@gmail.com';
    $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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?