PHP Switch case & if statement not returning correct values

Asked
Active3 hr before
Viewed126 times

8 Answers

statementreturningswitch
90%

The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for. , The statement list for a case can also be empty, which simply passes control into the statement list for the next case. ,Note: Note that unlike some other languages, the continue statement applies to switch and acts similar to break. If you have a switch inside a loop and wish to continue to the next iteration of the outer loop, use continue 2. , The following two examples are two different ways to write the same thing, one using a series of if and elseif statements, and the other using the switch statement:

(PHP 4, PHP 5, PHP 7, PHP 8)

The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for.

switch

(PHP 4, PHP 5, PHP 7, PHP 8)

The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for.

switch
load more v
88%

Unless you need to set a var to use later, I'd suggest the approach you have is perfectly fine. I knew the code's intent within 2 seconds from looking at it. Having a break just creates confusion.,PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case. For example:,we're trying to implement new coding style guidelines for our team, the php codesniffer is printing an warning on switch case statements when no "break" is found like:,Leaving a safety net break in is not a scenario of unforeseen circumstances, nor defensive programming. It's just bad coding, and you can't litter your code with back up code just in case you don't code correctly when you change something. That's such a bad approach to coding. The argument that "if someone removed return it won't work", well you could also have a typo in the case var, or forget to write the case, or...

But it's fairly common practise to add explicit breaks to every case as a defensive programming practise.

switch ($foo) {
   case 1:
      return 1;
      break;

   case 2:
      return 2;
      break;
}

That would accidentally cause program flow to fall through to case 2.

switch ($foo) {
   case 1:
      somethingDifferent();

   case 2:
      return 2;
      break;
}

Falling through case statements is slightly unusual and you should add a comment to your code when you do it to show that it's intentional.

switch ($foo) {
   case 1:
      somethingDifferentAndWeWantToDoCase2AsWell();
      // fallthrough

   case 2:
      return 2;
      break;
}
load more v
72%

Use the switch statement to select one of many blocks of code to be executed.,This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found.,The switch statement is used to perform different actions based on different conditions.,Create a switch statement that will output "Hello" if $color is "red", and "welcome" if $color is "green".

 ($color) {
    "red": echo "Hello";
    break;
    "green": echo "Welcome";
    break;
 }
65%

Switch is a control statement that allows a value to change control of execution.,There can be any number of case statements within a switch. Each case is followed by the value to be compared to and after that a colon.,When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.,Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached i.e. all the case statements will get executed as soon as compiler finds a comparison to be true.

Syntax:

switch (n) {
   case 1: // code to be executed if n = 1;
      break;
   case 2: // code to be executed if n = 2;
      break;
   default: // code to be executed if 
      // n doesn't match any cases
}

Syntax:

switch (n) {
   // code to be executed if n = 1;
   case 1:

      // Nested switch
      switch (num) {
         // code to be executed if num = 10
         case 10:
            statement 1;
            break;

            // code to be executed if num = 20
         case 20:
            statement 2;
            break;

            // code to be executed if num = 30
         case 30:
            statement 3;
            break;

            // code to be executed if num 
            // doesn't match any cases
         default:
      }

      break;

      // code to be executed if n = 2;
   case 2:
      statement 2;
      break;

      // code to be executed if n = 3;
   case 3:
      statement 3;
      break;

      // code to be executed if n doesn't match any cases
   default:
}
Output:
Choice is 2
load more v
75%

Code Line 5: We define two variables x, y = 8, 4,What happen when “if condition” does not meet ,Code Line 5: We define two variables x, y = 8, 8,Code Line 5: We define two variables x, y = 2, 8

Python if Statement Syntax:

if expression
Statement
else
   Statement
load more v
40%

Up to Fortran 77, the language Fortran has an "arithmetic if" statement which is halfway between a computed IF and a case statement, based on the trichotomy x < 0, x = 0, x > 0. This was the earliest conditional statement in Fortran:[11] ,depending on whether the else is associated with the first if or second if. This is known as the dangling else problem, and is resolved in various ways, depending on the language (commonly via the end if statement or {...} brackets). ,By using else if, it is possible to combine several conditions. Only the statements following the first condition that is found to be true will be executed. All other statements will be skipped. ,To accomplish the same using an if-statement, this would take more than one line of code (under typical layout conventions), and require mentioning "my_variable" twice:

If(boolean condition) Then(consequent)
Else
   (alternative)
End If
load more v
22%

Why will this below code not work? Instead of just putting in certain strings into each case I put in a boolean and asked the user how old they are. It just always logs the default statement no matter what I put into the prompt, and logs nothing if I have no default string to log. Appreciate any help!,but in this case your are as mtf already mentioned better of using an if statement instead.,switch() takes a variable with string or number type. The case is a fixed value that the argument is matched against. This is most useful when there are multiple branches.,So what will happen is that answer is compared to either true or false depending on what answer is and how this will evaluate this statement: answer < 18. So you always end up at the default case as a string is not a boolean. If you want to check for conditions in switches you can go on like this:

Why will this below code not work? Instead of just putting in certain strings into each case I put in a boolean and asked the user how old they are. It just always logs the default statement no matter what I put into the prompt, and logs nothing if I have no default string to log. Appreciate any help!

var answer = prompt("How old are you?");

switch (answer) {
   case (answer < 18):
      console.log("Ooh awkward, you are far too young to be running this code!");
      break;
   case (answer >= 18):
      console.log("Woohoo, let's play sunshine!");
      break;
   default:
      console.log("That was not a number!");
}
load more v
60%

One comparison to see whether the control condition evaluates to true (i < items.length == true),In each of these loops, there are several operations happening each time the loop body is executed:,Before the loop body is executed, the pretest condition is evaluated. If the condition evaluates to true, then the loop body is executed; otherwise, the loop body is skipped. Any for loop can also be written as a while loop and vice versa.,In a do-while loop, the loop body is always executed at least once, and the post-test condition determines whether the loop should be executed again.

for (var i = 0; i < 10; i++) {
   //loop body
}
var i = 0;
while (i < 10) {
   //loop body
   i++;
}
var i = 0;
do {
   //loop body
} while (i++ < 10);
for (var prop in object) {
   //loop body
}
load more v

Other "statement-returning" queries related to "PHP Switch case & if statement not returning correct values"