0

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 ?

5
  • 3
    Whatever you are trying to do, this is the wrong way. Commented Oct 6, 2016 at 14:28
  • 1
    If you remove "echo" and the smiley from the list() call you might get better results. Commented Oct 6, 2016 at 14:29
  • you mean : list($varname) ?? I tried this, but list isnt accepting this Commented Oct 6, 2016 at 14:30
  • @AbraCadaver Then how can i extract individual value from string n use them individually ? Yes, it can be done with code : foreach($hubba as $k=>$v){} , but without this ?? Commented Oct 6, 2016 at 14:33
  • You need to show what you have which is "value1, value2, value3, value4, value5, value6, value7" and what do you want it to look like or how do you need to use it. Commented Oct 6, 2016 at 14:35

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks mate. I knew this 2nd solution, but, i just happnd to go that way n found that its not working. Then i wanted to know the reason, that why list() isnt accepting that. Thanks anyways ! :)
This isn't really what list is for, but added more fun.
@luna.romania, one better way to say thanks is accepting the answer :)

Your Answer

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.