Search code examples
phpfor-loopvariable-variables

Variable variables created within a for loop


I'd like to change this:

if ($week_day == "1")
{
$day1_hours = $value;
}
if ($week_day == "2")
{
$day2_hours = $value;
}
if ($week_day == "3")
{
$day3_hours = $value;
}
if ($week_day == "4")
{
$day4_hours = $value;
}
if ($week_day == "5")
{
$day5_hours = $value;
}
if ($week_day == "6")
{
$day6_hours = $value;
}
if ($week_day == "7")
{
$day7_hours = $value;
}
}

Into something more readable, like a for loop, or whatever other suggestions you all may have.

I tried to do:

for ($c=1; $c<8, $c++)
{
if ($week_day == $c)
{
$day".$c."_hours = $value;
}
}

But I know that is nowhere near correct, and I have no idea how to insert another variable within a variable.

Any help is appreciated!


Solution

  • Try this syntax.

    ${'day'.$c.'_hours'} = $value;