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

dreeves
  • 26,430
  • 45
  • 154
  • 229

3 Answers3

40

Use list():

list($a, $b, $c) = $someArray;
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • Ha, figures PHP has an entire language construct, complete with a special reserved word, for this. Thanks, btw! – dreeves Feb 02 '10 at 08:03
12

Use list

$arr = array(1,2,3);
list($a, $b, $c) = $arr;
ariefbayu
  • 21,849
  • 12
  • 71
  • 92
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

wheelmaker
  • 2,975
  • 2
  • 21
  • 32