Mastrianni
Mastrianni

Reputation: 3930

How to pass an array of variable names to list()

I'm trying to pass an array of variable names to be assigned to the list() function, and I'm wondering if it's even possible. My intention is for list($variables) to parse $values.

$variables = array("$var1","$var2","$var3");
$values = array('Value1','Value2','Value3');

//Can I simply pass an array of variable names to be assigned here
list($values) = explode("&", $values);

To clarify, my intention is to have PHP execute this:

list($var1, $var2, $var3) = explode("&", $values);

Upvotes: 0

Views: 1029

Answers (5)

Vero
Vero

Reputation: 1750

I understand you want to explode the response variable and assign each value to the corresponding variable.

You can achieve it this way instead of using list:

$varnames = array('var1','var2','var3');
$varvals  = explode('&',$response);
foreach($varnames as $k => $v){
    $$v = $varvals[$k];
}

This way $var1 will have the first value in response, $var2 the second, and so on.

Upvotes: 0

dave
dave

Reputation: 64657

You'd have to do a little trickery, but with array_combine and extract you could achieve the same effect:

$keys = array("var1","var2","var3");
$values = array('Value1','Value2','Value3');
extract(array_combine($keys, $values));
echo $var1; //"Value1"

Upvotes: 2

S.Pols
S.Pols

Reputation: 3434

list is used to assign a list of variables in one operation. This is the sytax:

$string = 'VarA, VarB, VarC';
list($varA, $varB, $varC) = explode(',', $string);

When u use variables you can need to keep the quotes away so the second is the right one.

$array = ($var1, $var2, $var3);

You dont need to use explode anymore cause you already have an array. explode creates an array. In your example it would be:

$array = array($var1, $var2, $var3);
list($varA, $varB, $varC) = $array;

Note that i changed the array syntax. You forgot the array keyword.

Upvotes: 0

Razip
Razip

Reputation: 155

You can't do that. Why you don't use the second your variant?

Upvotes: -1

user1954544
user1954544

Reputation: 1687

<?php

$info = array('coffee', 'brown', 'caffeine');

// Listing all the variables
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";

// Listing some of them
list($drink, , $power) = $info;
echo "$drink has $power.\n";

// Or let's skip to only the third one
list( , , $power) = $info;
echo "I need $power!\n";

// list() doesn't work with strings
list($bar) = "abcde";
var_dump($bar); // NULL
?>

http://php.net/manual/en/function.list.php

Upvotes: 1

Related Questions