JohnMazz
JohnMazz

Reputation: 33

Assign array items to individual variables on one line

I have a chunk of code like:

<?php
$person = array("John", "Smith", "Male", "Green");
$firstN = $person[0];
$lastN = $person[1];
$gender = $person[2];
$favColor = $person[3];
?>

I saw some code once that consolidated this, but I can't figure out how it was done, and can't find the page where I saw the example. It was something like:

<?php
$person = array("John", "Smith", "Male", "Green");
someFunction($firstN, $lastN, $gender,$favColor) = $person;
?>

It assigned the variables based on the values in the array in the same way the first example did it.

What could someFunction be in the above example?

Upvotes: 0

Views: 90

Answers (2)

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174977

Why yes! There's actually a cool way to do that:

list($firstN, $lastN, $gender, $favColor) = $person;

And that's it! All the variables would be populated.

See list() PHP manual entry.

Upvotes: 2

j08691
j08691

Reputation: 207900

You're probably looking for PHP's list() function.

Ex:

$info = array('coffee', 'brown', 'caffeine');
// Listing all the variables
list($drink, $color, $power) = $info;

In your case:

$person = array("John", "Smith", "Male", "Green");
list($firstN, $lastN, $gender,$favColor) = $person;

Upvotes: 2

Related Questions