23

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.]

asked Feb 2, 2010 at 7:57

3 Answers 3

40

Use list():

list($a, $b, $c) = $someArray;
answered Feb 2, 2010 at 7:59
Sign up to request clarification or add additional context in comments.

1 Comment

Ha, figures PHP has an entire language construct, complete with a special reserved word, for this. Thanks, btw!
12

Use list

$arr = array(1,2,3);
list($a, $b, $c) = $arr;
answered Feb 2, 2010 at 8:01

Comments

1

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

answered Dec 26, 2019 at 21:31

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.