I have been making a clock which displays schedules based on which day it is so I have created 7 arrays with schedules in them. Now I need to write a foreach statement that takes the date:
$day = date("D");
Then uses the foreach function on that array like:
foreach ($day as &$value) {
}
When I do this though it gives me an error because it wants me to use the direct array variable.
Warning: Invalid argument supplied for foreach() in /home/johfin16/johnfinberg.com/php/functions-new.php on line 24
Here is an example of one of my arrays.
$Mon = array("08:10am-08:30am-Morning Meeting",
"08:35am-09:55am-A Block",
"10:05am-11:25am-B Block",
"11:30am-12:05pm-First Lunch",
"12:05pm-12:40pm-Second Lunch",
"12:40pm-02:00pm-C Block",
"02:05pm-03:25pm-D Block");
Is there a way to work around this without creating a bunch of if statements?
It looks like you're trying to use variable variables. So it should be:
$day = &${date('D');
foreach ($day as &$value) {
...
}
However, variable variables are generally poor programming practice. Whenever you find yourself needing them, it's a sign that you should be using an associative array instead of separate variables. So your code should be:
$calendar = array(
'Mon' => array("08:10am-08:30am-Morning Meeting","08:35am-09:55am-A Block", "10:05am-11:25am-B Block", "11:30am-12:05pm-First Lunch", "12:05pm-12:40pm-Second Lunch", "12:40pm-02:00pm-C Block", "02:05pm-03:25pm-D Block"),
'Tue' => array(...),
...
);
Then you can do:
$day = &$calendar[date('D')];
foreach ($day as &$value) {
...
}
The switch function can be used to set one array to $active and then that array can be used in the foreach function. Ex:
switch ($day) {
case "Mon":
$active = $Mon;
break;
case "Tue":
$active = $Tue;
break;
case "Wed":
$active = $Wed;
break;
default:
$active = $Special;
}
In each day there are multiple classes which need to be pulled from the array.
NO
Because you have:
$day = date("D");
So whatever $day contained before this line is reached, classes, arrays, variables, etc. is forgotten and $day suddenly just becomes ONLY the result of date("D").
You may be wanting to add date("D") as an array element (ie one of numerous items in an array), therefore you would do:
$day[] = date("D");
This will add the date("D") value to an array of multiple $days, this can then be cycled through with a foreach loop. For each day.