Switching a conditional case in php - php

I use javascript to send cases to and ajax function. The cases are taken from the link id. For example, if user clicked this link:
<a id="answer-yes-123">click this</a>
The javascript will split the id to 3 part, and send the middle part "yes" to ajax as a case. For most cases, when ajax receives the case, if yes do this if no do that.
switch ($case) {
case 'yes' :
$assignment->add();
break;
case 'no' :
$assignment->remove();
break;
There's one exception-- a numerical case. If the middle part of the link is a number, I don't know how to make the switching statement. There are potentially unlimited different numbers, I can't make each of them a case, How to make a condition like if(is_int($case)) to work as a case?

In the switch default: case, you can test is_int():
switch ($case) {
case 'yes' :
$assignment->add();
break;
case 'no' :
$assignment->remove();
break;
default:
// Determine the numeric value however you need to
// is_int(), is_numeric(), preg_match(), whatever...
if (is_int($case)) {
// numeric stuff
}
}
This is a little strange logically, because default: is typically used for the do this if nothing else is met condition. In your case though, if you don't need to further divide the numeric case much it works. Just be sure to comment it clearly in your code so you remember why you did it when you look back on it in six months.
Update after comments:
Since you already used the default:, I believe you can actually use an expression inside a case. This warrants even clearer commenting since it is not a common practice and goes kind of against the purpose of a switch:
switch ($case) {
case 'yes' :
$assignment->add();
break;
case 'no' :
$assignment->remove();
break;
// This actually works, but is highly weird.
// One of those things I can't believe PHP allows.
// is_int(), is_numeric(), preg_match(), whatever...
case is_int($case):
// Numeric stuff
break;
default:
// default stuff
}

Write the if-statement around the switch.
Something like this comes to my mind:
if (is_int($case)) {
// ...
} else {
switch ($case) {
// ...
}
}

Michael Berkowski's answer is perfect, but if don't want to use default case like this that could work also:
switch (preg_replace('/^[0-9]*$/','numeric',$case)) {
case 'yes' :
$assignment->add();
break;
case 'no' :
$assignment->remove();
break;
case 'numeric' :
$assignment->remove();
break;
default:
//...
break;
}

Use PHP's is_numeric
http://php.net/manual/en/function.is-numeric.php
if (is_numeric($case)) {
// ...
} else {
switch ($case) {
// ...
}
}

Related

How I can make switch case check all cases

What if I want to make each case in the switch case been a equlity condition like this code example
switch (true){
case X==Y:
//do something
case X==Z:
//do something
case X has 0 :
//do something
}
Its working well if I want to check only one condition,By adding break
,But what if i want to check all cases and do only true cases
If you want to change flavor from if.....else and want to use switch....case
So you can try like this
$test = true;
$x=1;$y=1;$z=2;//uncomment any one and check
//$x=1;$y=2;$z=1;//uncomment any one and check
//$x=0;$y=1;$z=1;//uncomment any one and check
switch ($test){
case $x==$y:
echo "x==y";
break;
case $x==$z:
echo "x==z";
break;
case $x==0 :
echo "x has 0";
break;
default:
echo "he!he!he!he!he!he!";
}
uncomment any one and check all conditions
Check demo here : https://eval.in/907483
Here using $test = true; means if your condition goes true in case inside switch

A better PHP switch command

In pick basic there is a case command which functions similar to the switch command basically doing nested if then else commands. The code is like this:
begin case
case a=4;do something
case b=5 or c=6;do something
case y=x and f=z;do something
case 1;do something
end case
if any of the conditions are true, it falls into that case. I know PHP has the switch command, but that is limited to the value of one variable. Is there a way to code the above in PHP or javascript for that matter without a bunch of if then else commands similar to the above?
If you really don't want to use if/else, then switch (true) can work:
switch (true) {
case ($a === 4):
doSomething();
break;
case ($b === 5 || $c === 6):
doSomething();
break;
case ($y === $x || $f === $z):
doSomething();
break;
default:
break;
}
However, it is less typing, and it makes your code more readable, if you simply use if/else instead, just as Shomz suggested. I really wouldn't recommend using switch (true).
Replacing case with else if is only 3 bytes longer, I don't see the big deal because that is exactly what the if/else is for. Switches are used for single variables, as you said.
Your do something could also include a result variable or a flag that will be set if any of the conditions are met.
So this:
begin case
case a=4;do something
case b=5 or c=6;do something
case y=x and f=z;do something
case 1;do something
end case
could be:
var case = false;
if (a==4) {dosomething(); case = true}
else if (b==5 || c==6) {dosomething(); case = true}
else if (y==z || f==z) {dosomething(); case = true}
else if (1) {dosomething(); case = true} // supposedly the default case?

How to loop through all cases in switch if they are all true

I have a switch statement with 3 cases,like this:
switch($date) {
case 1:
echo "";
break;
case 2:
echo "";
break;
case 3:
echo'';
break;
default:
echo '';
break;
}
And i am wondering,if there is a way to loop through all cases if they are all true.But with using break,because if i am not using it,the cases wont work properly.So is there a way???
You shouldn't use switch if you want to see if multiple things are true about the variable in question since the switch statement will cut out once one of the cases holds true (i.e. it won't continue to look to see if the other cases also apply to the variable).
If your goal is to test if multiple things are true regarding a variable, just use an if statement:
if ($date == X && $date == Y && $date == Z) {
// Do something since all the conditions are met
}
Another possibility is to "fall through" your cases like this:
switch ($variable) {
case 0:
// Do something to (some) variable to indicate this case applies
case 1:
// Do something to (some) variable to indicate this case also applies
case 2:
// Do something to (some) variable to indicate this case also applies
echo "WHATEVER YOU WANT TO ECHO"
break;
}

PHP string switch using NOT operator

I have a small switch statement in the header of a portfolio website I'm working on which governs which links are shown on which page. The value of $id comes from the GET variable, ie - '?id=index'.
switch($id) {
case "index":
//Show links to content
case !"index":
//Show link to index
case !"about":
//show link to about page
}
The issue is that the NOT operator isn't working in the final two cases. I want the link to the index to show when the user is NOT on the index page, and likewise with the about page. Currently, ALL links are shown on the index page (when $id == "index), and NONE are shown on any other pages.
Why might this be?
This is so, because it is supposed to be so.
switch compares using the == operator. So in the second case, you are actually testing whether
$id == (!"index")
Which will always evaluate to false since any string would be trueand not true would be false.
Which means, in your case it would be better to use if and else.
Sorry, but what you're trying to do is simply not valid syntax for a switch / case construct.
The closest you'll come to what you're looking for is to use the default option. This works like a final case option, that deals with all values that were not caught by any of the preceding cases.
switch($id) {
case "index":
//Show links to content
case "about":
//Show link to about page
default:
//show link to default page.
}
Also - don't forget the break; at the end of each case block, otherwise it'll fall through to the next one, which can lead to some unexpected bugs.
!"index" will probably evaluate as false (but I'm little surprised it didn't cause syntax error) and you'll actually having this statement:
switch($id){
case "index": //...
case false: // ...
case false: // ...
}
When you want to use switch, you'll need to do is this way:
switch($id){
case "index": // ...
case "about": // ...
default:
// Additional statements here, note that $id != "index" is already covered
// by not entering into case "index"
}
What your code is doing is comparing $id against three values: "index", !"index" (whatever it means) and !"about".
I'm not sure about your approach. You should try if/else or ternary operators.
Hope that it helps.
Switch doesn't offer custom operators.
switch ( $id ) {
case 'index':
// $id == 'index'
break;
case 'about':
// $id == 'about'
break;
case 'help':
case 'info':
// $id == 'info' or $id == 'help'
break;
default:
// all other cases
}
The switch case does not accept complex expressions. The not ! operator is a logical operator. It works in expressions like this.
!$x; // true if $x = false
or as a comparison operator:
$a != $b; // Not equal
// or
$a !== $b // not identical
From the manual.
The case expression of the switch statement may be any expression
that evaluates to a simple type, that is, integer or floating-point
numbers and strings. Arrays or objects cannot be used here unless they
are dereferenced to a simple type.
surely you can fix this with:
switch($id){
case ($id != 'index'):
echo 'this is not index';
break;
case 'index':
echo 'this is index';
break;
case 'foo':
echo 'this is foo!';
break;
default:
break;
}
However, this example is flawed, because the first case statement will just catch anything that isn't 'index' thus you shouldn't ever get to the case 'foo' nor the default statement

Multiple Separate Switch Statements

I have multiple switch statements in on one of the pages in order to pass different variables to the URL, as well as different case. I need these different switch statements because I need the different variables.
However, when I put a "default" in one of the switch statements, that default applies to every other switch statement and so when I use the variable of another switch statement in the URL, the default case of that other switch statement will appear on screen, along with the case of this switch statement.
All of my switch statements have one or more cases and I really cannot figure out how to get around this. Please may somebody help me?
Thanks in advance,
Calum.
This might be way off, but I think you need something like this:
if (isset($_POST['myvar'])) {
switch ($_POST['myvar'] {
case 1:
....
break;
default:
....
break;
}
} else if (isset($_POST['myvar2'])) {
switch ($_POST['myvar2'] {
case 1:
....
break;
default:
....
break;
}
}
Does that make sense?
make sure that you have a "break;" statement at the end of each of your cases, and that the default case is the last one. like this:
switch ($var) {
case 1: // do stuff 1;
break;
case 3: // do stuff 2;
break;
// ...
default: // do default stuff
}

Categories