0

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!

RobDubya
  • 93
  • 1
  • 1
  • 8
  • 1
    Wouldn't it be easier to set an array key? `$day[$week_day] = $value` – andrewsi Jul 03 '13 at 00:50
  • Perhaps! Elaborate on that? – RobDubya Jul 03 '13 at 00:51
  • @RobDubya .... That's pretty much it, actually :D – andrewsi Jul 03 '13 at 00:51
  • Check manual for more info http://php.net/manual/en/language.types.array.php. Please try your own code. Posting invalid syntax doesn't show an attempt at solving the problem... – elclanrs Jul 03 '13 at 00:52
  • Could you post the full code for this situation as an answer? Declaring the array and so on? – RobDubya Jul 03 '13 at 00:52
  • @RobDubya - it's literally one extra line, the where you declare the array. You'll end up with an array where the key is the $week_day value, and the value is whatever's in $value. – andrewsi Jul 03 '13 at 00:55
  • I also need the _hours portion of the variable for stuff further along in the code, will it keep that, so would $day[$week_day]_hours = $value work? – RobDubya Jul 03 '13 at 01:00
  • You can replace it with `$day[$week_day]` - that's what you're setting value to – andrewsi Jul 03 '13 at 01:12

4 Answers4

1

Try this syntax.

${'day'.$c.'_hours'} = $value;
sectus
  • 15,605
  • 5
  • 55
  • 97
0

Try this

$hours[$week_day] = $value
Kris
  • 6,094
  • 2
  • 31
  • 46
0

Something like this

$week_day = 3;
$value = "hi";

${"day" . $week_day . "_hours"} = $value;  

echo $day3_hours;
Lloyd Banks
  • 35,740
  • 58
  • 156
  • 248
0

My interpretation.

$week = 7;
$day = array();

for($i=1; $i<=7; $i++){
   $day[$i]['hours'] = $value;
}

You can declare the numbers of weeks you want and to pull the data you can do something like this:

echo $day[1]['hours']
Drixson Oseña
  • 3,631
  • 3
  • 23
  • 36