Michiel
Michiel

Reputation: 8103

Strange switch-statement behavior

Can someone show me why this switch statement doesn't output the same as the if statement? And more important, how do I get them to output the same?

Switch

switch ($list_day) { 
        case $today : 
            $calender .= '<td class="today">';
        default : 
            $calender .= '<td>';
    }

If

if ($list_day == $today) {
        $calendar.= '<td class="today">';
    } else {
        $calendar.= '<td>';
    }

Upvotes: 0

Views: 83

Answers (3)

Mathieu Dumoulin
Mathieu Dumoulin

Reputation: 12244

You have a typo:

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

As well as the break i previously submitted, you typed $calender instead of $calendar...

Upvotes: 1

Mathieu Dumoulin
Mathieu Dumoulin

Reputation: 12244

You forgot your BREAK;

In Pascal style code such as pascal, visual basic, you don't need to BREAK on each case. But in C-Style/Java/PHP/etc you need:

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

This can be used to do some fancy things that i'll let you figure out yourself!

Upvotes: 1

knittl
knittl

Reputation: 265918

You are missing your break statements:

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

If you don't break out of the switch statement execution just continues with the next label. This allows you to chain labels together:

switch($number) {
case 1: case 2: case 3:
  echo '1 - 3';
  break;
case 4:
  echo '4';
  break;
default
  echo 'any other number';
}

Upvotes: 4

Related Questions