微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PHP“列表”问题:为什么结果的顺序相反?

你能否详细解释为什么这段代码

$arr = array(1, 2, 3);
list($result[], $result[], $result[]) = $arr;
print_r($result);

结果是:

Array ( [0] => 3 [1] => 2 [2] => 1 ) 

解决方法:

请参阅listPHP文档:

list() assigns the values starting with the right-most parameter. If you are using plain variables, you don’t have to worry about this. But if you are using arrays with indices you usually expect the order of the indices in the array the same you wrote in the list() from left to right; which it isn’t. It’s assigned in the reverse order.

如果你想知道为什么会这样做,那么原因可能是,使用LALR(1)解析器更容易实现从右到左的赋值,在这里你通常只使用左手边递归,这是出于性能原因:

assignment_list:
      assignment_list ',' assignment_list_element
    | assignment_list_element
;

assignment_list_element:
      variable    { zend_do_add_list_element(&$1 TSrmlS_CC); }
    | T_LIST '('  { zend_do_new_list_begin(TSrmlS_C); } assignment_list ')' { zend_do_new_list_end(TSrmlS_C); }
    | /* empty */ { zend_do_add_list_element(NULL TSrmlS_CC); }
;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐