首页 > 闹鬼!php字符串数组交叉

闹鬼!php字符串数组交叉

$where = '1=1';
$keyword = $_GET['keyword'];
        
if($keyword) {
    $where['title'] = array('like', "%$keyword%");
}

var_dump($where);

竟然打印出来:A=1

到底是怎么样的转换流程?

首先,让我来吐槽一下(不吐槽会死!):

  1. $where是一个字符串,你写的$where['title']是个什么鬼?

  2. 你把一个array赋值给一个字符串中的一个字符串,这又是什么鬼?

我把你问题中的一些杂七杂八无用的代码去除后,精简一下问题:

$where = '1=1';
$where['title'] = array();
var_dump($where);

和上面的吐槽对应的是,我们也一步步来看:
$where['title']表达的是字符串$where中下标为'title'的字符,注意下标的合法值是[0-字符串长度减1],那么php对于非法的下标,实际上是和$where[0]的作用是一致的。
这样问题进一步简化为:

$where = '1=1';
$where[0] = array();
var_dump($where);

了解了$where[0]实际上指的是$where字符串的第一个字符,那么下面就是要吐槽的“你把一个array赋值给一个字符串中的一个字符串,这又是什么鬼?
我们下面做一个测试:

var_dump( (string)array() );

你猜会输出什么?

PHP Notice:  Array to string conversion in /home/nfer/temp.php on line 8
string(5) "Array"

那么这里就很好理解了,$where[0] = array();就是把字符串Array赋值给$where字符串的第一个字符。
bingo, the output is string(3) "A=1"

最后,让我也写一个闹鬼的代码:

$where = 'A=1';
$keyword = $_GET['keyword'];
        
if($keyword) {
    $where['title'] = $keyword == 123;
}

var_dump($where);

你觉得结果会输出什么呢?


1.$where = 1,这个没错把,首先这个是字符串。
2.然后你又把$where当数组,并把$where['title'] = array('like',"xxx"),赋值过去,这不科学把。

【热门文章】
【热门文章】