luna.romania
luna.romania

Reputation: 307

How can i use dynamically generated string inside `list() = $variable`?

I am trying to dynamically generate a string n then use it inside list() to catch array values in variables.

Code :

<?php

$bubba = "value1, value2, value3, value4, value5, value6, value7";

$hubba = explode(",", $bubba);

$num = count($hubba);

ob_start();

for($i=1; $i<=$num; $i++){

    echo ('$k'.$i.', ');

}

$varname = ob_get_clean();

$varname = substr($varname, 0, -2);

list(echo $varname;) = $hubba;

I want this to look like:

list($k1, $k2, $k3, $k4, $k5, $k6, $k7) = $hubba;

echo $k1; // must echo value1

?>

But, list simply is not-ready to accept the variable string. How to do this ?

Upvotes: 0

Views: 36

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

You are trying to solve a problem the wrong way. Most experienced developers will tell you that they have been down this road and it's a dead end. Why use $k0 instead of the existing $k[0]? However, for fun, here is a working example:

extract($hubba, EXTR_PREFIX_ALL, 'k');
echo $k_0;

Or another, for fun, that does it the way you describe:

foreach($hubba as $k => $v) {
    ${'k'.($k+1)} = $v;
}
echo $k1;

Or finally, for more fun, using list() for no apparent reason:

for($i=1; $i<=$num; $i++) {
    $var[] = '$k'.$i;
}
$vars = implode(', ', $var);

eval("list($vars) = \$hubba;");

echo $k1;

I would encourage you to include WHY you think you need this and there is definitely a better solution.

Upvotes: 1

Related Questions