Michiel
Michiel

Reputation: 8083

Foreach inside a switch-statement

How can I enclose a foreach-loop inside a switch-statement?

I've got something like this (don't know if it's correct though):

    $activiteiten = array(2,9,11);

    switch ($list_day) { 
            case $today : 
                $calendar.= '<td class="today">';
                break;

             foreach ($activiteiten as &$value) {
                case $value : 
                $calendar .= '<td class="date_has_event">';
                break;
             }

            default : 
                $calendar .= '<td>';
        }

The error I get is "Parse error: syntax error, unexpected T_CASE in ..."

Upvotes: 1

Views: 8433

Answers (3)

hakre
hakre

Reputation: 197775

Actually it's your default case:

$activiteiten = array(2,9,11);

switch ($list_day)
{ 
    case $today:

        $calendar .= '<td class="today">';
        break;

    default:

         foreach ($activiteiten as $value)
         {
            if ($list_day === $value)
            {
                $calendar .= '<td class="date_has_event">';
                break 2; # !!
            }
         }

        $calendar .= '<td>';
}

But instead you could (should) use some logic first to get the $class and if it's still empty, create an empty <TD> element, if it's set, create a <TD class="..."> element.

Upvotes: 3

472084
472084

Reputation: 17885

PHP does not allow you to create case statements programmatically.

How about this:

$activiteiten = array(2,9,11);

if ($list_day == $today){
    $calendar.= '<td class="today">';
}elseif(in_array($list_day, $activiteiten)){
    $calendar .= '<td class="date_has_event">';
}else{
    $calendar .= '<td>';
}

Upvotes: 3

KingCrunch
KingCrunch

Reputation: 131891

Not possible this way. You may try something like

if (in_array($list_day, $activiteiten))

instead

Upvotes: 1

Related Questions