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!

8
  • 1
    Wouldn't it be easier to set an array key? $day[$week_day] = $value Commented Jul 3, 2013 at 0:50
  • Perhaps! Elaborate on that? Commented Jul 3, 2013 at 0:51
  • @RobDubya .... That's pretty much it, actually :D Commented Jul 3, 2013 at 0:51
  • Check manual for more info 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... Commented Jul 3, 2013 at 0:52
  • Could you post the full code for this situation as an answer? Declaring the array and so on? Commented Jul 3, 2013 at 0:52

4 Answers 4

1

Try this syntax.

${'day'.$c.'_hours'} = $value;
Sign up to request clarification or add additional context in comments.

1 Comment

No joy, loads a blank page.
0

Try this

$hours[$week_day] = $value

Comments

0

Something like this

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

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

echo $day3_hours;

Comments

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.