Switch Case : Doubts

Whats In Name

Whats In Name

@whats-in-name-KdgM7o Oct 26, 2024
Ok,I got to clear 2 doubts associated with the classic "Switch Case"-
<?php
$favcolor
="red";
switch (
$favcolor)
{
default:
  echo 
"Your favorite color is neither red, blue, or green!";
case 
"red":
  echo 
"Your favorite color is red!";
case 
"blue":
  echo 
"Your favorite color is blue!";
  break;
case 
"green":
  echo 
"Your favorite color is green!";
  break;
?>
1)What "break" does is exits the case and brings to the end of switch case,I have omitted "break" from case "red"..So it comes to case "blue" but it should only enter case "blue" when it is true(which is not,right now),right?,then why my output is like this-

Output::
Your favorite color is red!Your favorite color is blue!

2)When I shifted default after case "red" and omitted break from case "red" it was executing default too!(Why?),but when I shifted default at the top of the block it was not executing.

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • Anoop Kumar

    Anoop Kumar

    @anoop-kumar-GDGRCn Jan 29, 2013

    Switch logic will continue to execute after finding its match, until it finds a break; statement.
    and logically default case should be last case.I don't know PHP but in java it should throw a compile error.
  • rahul69

    rahul69

    @rahul69-97fAOs Jan 29, 2013

    Well well Switch Cases!!😕.
    Let's see your doubts one by one:

    but it should only enter case "blue" when it is true(which is not,right now),right?,then why my output is like this-

    Output::
    Your favorite color is red!Your favorite color is blue!
    The fact is : If you remove break statement, it will execute all statements, after a matching condition unless it faces a break statement.
    So it will enter case blue without checking, and continue this behavior unless it sees a break.

    When I shifted default after case "red" and omitted break from case "red" it was executing default too!(Why?),but when I shifted default at the top of the block it was not executing.
    Now as we know default only executes after all cases have failed, so it doesnot execute at the top (since some other case matches),but when you place it under "red" it executes due to the reason of your first question (ie no break present).
    And one more thing, u didn't closed (ie.}) your switch in the code u pasted, so ideally it should give an error😉 .
    Hope this answers your doubts!!👍
  • Whats In Name

    Whats In Name

    @whats-in-name-KdgM7o Jan 30, 2013

    Okay,so the thing is-after matching condition it continues until it finds a "break".
    Thanks a lot for the answers, both of you and thanks for the detailed explanation #-Link-Snipped-#