Parallel array assignment in PHP

主宰稳场 提交于 2019-12-30 05:36:09

问题


Most languages make it easy to take an array like [1, 2, 3] and assign those values to variables a, b, and c with a single command. For example, in Perl you can do

($a, $b, $c) = (1, 2, 3);

What's the corresponding trick in PHP?

[Thanks so much for the lightning fast answer! I know this is a trivial question but all the obvious google queries didn't turn up the answer so this is my attempt to fix that.]


回答1:


Use list():

list($a, $b, $c) = $someArray;



回答2:


Use list

$arr = array(1,2,3);
list($a, $b, $c) = $arr;



回答3:


As of PHP 7.1 you can use the list shorthand [] for array destructuring.

[$a, $b, $c] = [1, 2, 3];

Also as of 7.1 you can destructure non-numerically keyed arrays similar to the way that object destructuring works in ES6. https://stitcher.io/blog/array-destructuring-with-list-in-php



来源:https://stackoverflow.com/questions/2182563/parallel-array-assignment-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!