-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

5
  • 1
    Can you tell us your expected result because it's impossible to loop inside a list Commented Apr 19, 2022 at 10:18
  • $list[0], $list[1] etc already has what you need. Commented Apr 19, 2022 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 Commented Apr 19, 2022 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. Commented Apr 19, 2022 at 11:40
  • This'll get you very close: stackoverflow.com/a/52393728/2943403 3v4l.org/9Xbc5 Commented Apr 19, 2022 at 11:48

2 Answers 2

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;
?>
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.