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

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...