Single foreach loop statement on dynamically named arrays with a common prefix?
-
12-06-2021 - |
Question
$size_of_groups = "4";
// for the purpose of the question, assume $seeded_teams size is currently 32, it's array that returns data from a function i have created,
//however the size can change
// depending on user input
// creates dynamically named arrays (i realize this is a poor way of doing
//things, but, for my purposes it is fine
$ft = "true";
for ($i = 1; $i < sizeof($seeded_teams) / $size_of_groups + 1; $i++) {
if ($ft == "true") {
${"group{$i}"} = array($seeded_teams[0], $seeded_teams[sizeof($seeded_teams) / 2 - 1],
$seeded_teams[sizeof($seeded_teams) / 2], $seeded_teams[sizeof($seeded_teams) - 1]);
$ft = "false";
} else {
${"group{$i}"} = array($seeded_teams[-1 + $i], $seeded_teams[sizeof($seeded_teams) / 2 - $i],
$seeded_teams[sizeof($seeded_teams) / 2 - 1 + $i], $seeded_teams[sizeof($seeded_teams) - $i]);
}
}
I am creating arrays with dynamic names in my script. All arrays created this way are appended with a number.
For example: $group1, $group2, $group3, $group4, $group5, $group6, $group7, $group8
If I know (and my script understands) exactly how many arrays there are (and as a result, will know all of the appensions), I was wondering if there was anyway to execute a single statement that understands to go through all 8 of those arrays without having to call 8 seperate loops.
I imagine that it would probably be much better to just rewrite this portion of the code to use multidimensional arrays but I wrote a few other functions using this information quite a while ago when I was far less experienced, and hadn't realized the scope of the project. Note, this project is for personal purposes only.
To give a better example, is it possible to do something like this?
for($i=0;$i < $number_of_groups + 1; i++) {
foreach ($"{group{$i}"} as $value) {
echo $value."<br>";
}
}
Solution
You can accomplish this with variable variables
:
for($i = 0; $i < $number_of_groups + 1; i++) {
$var = 'group' . $i;
foreach ($$var as $value) {
// ...
}
}