-2

Is there any way to create a loop of variables inside list() I've tried this code but it doesn't work.

$long_string = "one , two , three , four";
$list = explode(" , ",$long_string);
$count_list = count($list);

list(for($i = 0; $i <= $count_list; $i++){ return ${"list$i"}; }) = explode(" , ",$long_string);

Update : Got the solution, thanks

S4NHXNU1
  • 3
  • 2
  • 1
    Can you tell us your expected result because it's impossible to loop inside a list – Youssef Saoubou Apr 19 '22 at 10:18
  • `$list[0]`, `$list[1]` etc already has what you need. – u_mulder Apr 19 '22 at 10:19
  • @Youssef I trying to explode the string and set the variable for them but not fixing the amount of array. As normal in order to use `list()` it must be `list($variable1, $variable2, $variable3, $variable4) = explode(" , ",$long_string);` right? but in this case I trying to create a loop for the variable instead – S4NHXNU1 Apr 19 '22 at 10:57
  • Variable variables is a symptom that you should be declaring an array structure, but you are deliberately limiting the tools that you can use by avoiding an array structure. I'm calling this question an XY Problem. – mickmackusa Apr 19 '22 at 11:40
  • This'll get you very close: https://stackoverflow.com/a/52393728/2943403 https://3v4l.org/9Xbc5 – mickmackusa Apr 19 '22 at 11:48

2 Answers2

0

you may use a while to produce the vars:

php < 7.2 :

<?php
$long_string = "one , two , three , four";
$list = explode(" , ",$long_string);
while (list($key, $val) = each($list)) {
    ${"list".$key} = $val;
}
print_r($list0); //returns one
print_r($list1); //returns two

PHP > 7.2: Alternate way

    <?php
     $long_string = "one , two , three , four";
     $list = explode(" , ",$long_string);
     foreach($list as $key => $val) ${"list".$key} = $val;
     echo $list0;
     echo $list1;
?>
Milad Elyasi
  • 789
  • 4
  • 12
0

I can't think of a way to use list() for this. You're also returning from the loop in the first iteration, what doesn't make a lot of sense, and doing some redundant calculations. Additionally, you're creating one too many $list variables (0 to 4 are 5 variables for only 4 items).

All you need is:

foreach (explode(' , ', $long_string) as $k => $v) {
    ${"list$k"} = $v;
}

In any case, I have my concerns about the overall design. You already have a handy array thanks to explode(), and that feels more usable than independent variables popping up from nowhere which you can't easily list or enumerate.

Álvaro González
  • 142,137
  • 41
  • 261
  • 360