Here is my code I wanted to ask if there is a better way to do this? I'm going to need more "else if" options and I'm worried about performance
if($_GET['begin'] === 'yeg'){
} else if ($_GET['begin'] === 'deda') {
} else if ($_GET['begin'] === 'beara') {
} else if ($_GET['begin'] === 'eima') {
} else if ($_GET['begin'] === 'aba') {
}
You should use switch statement instead. A switch construct is more easily translated into a jump (or branch) table. This can make switch statements much more efficient than if-else when the case labels are close together. The idea is to place a bunch of jump instructions sequentially in memory and then add the value to the program counter. This replaces a sequence of comparison instructions with an add operation. - #Judge Maygarden
Why the switch statement and not if-else?
$begin = $_GET['begin'];
switch ($begin):
case 'yeg':
//do something
break;
case 'deda':
//do something
break;
case 'beara':
//do something
break;
case 'eima':
//do something
break;
case 'aba':
//do something
break;
endswitch;
You can try to use a switch statement instead:
switch ($_GET['begin']) {
case 'yeg':
break;
case 'deda':
break;
// Yada yada, continue like this as much as needed.
}
Related
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?
Pages such as this: PHP switch case $_GET's variables and switch case $_GET's variable's values and others have helped, but I am at a loss as to why my switch statment does not work.
A user may be directed to my page with index.php?class=className&badge=badgeName or index.php?class=className or index.php?badge=badgeName or just plain old index.php
This code works just fine
if ($_GET["badge"] && $_GET["class"]) {
echo 'Badge and Class';
} elseif ($_GET["badge"] && !$_GET["class"]) {
echo 'Badge only';
} elseif (!$_GET["badge"] && $_GET["class"]) {
echo 'Class only';
} else {
echo 'No variables';
}
But I was trying to simplify with a switch statement, whereby all works well except for the default case:
switch ($_GET) {
case $_GET["badge"] && $_GET["class"]:
echo 'Badge and Class';
break;
case $_GET["badge"] && !$_GET["class"]:
echo 'Badge Only';
break;
case !$_GET["badge"] && $_GET["class"]:
echo 'Class only';
break;
default:
echo "No badge or class";
}
Any help appreciated.
You can try something like this:
switch (true) {
case ($i ==0):
echo '$i ==0';
break;
case ($i < 1):
echo '$i < 1';
break;
case ($i > 1):
echo '$i > 1';
break;
}
For your case:
switch (true) {
case ($_GET["badge"] && $_GET["class"]):
echo 'Badge and Class';
break;
case ($_GET["badge"] && !$_GET["class"]):
echo 'Badge Only';
break;
case (!$_GET["badge"] && $_GET["class"]):
echo 'Class only';
break;
default:
echo "No badge or class";
}
As the answer are in the link you gave:
You have to enclose the switch in a foreach() loop.
$_GET is simply an array, so you will have to make a for-each loop over it, as proposed in the link
foreach ($_GET as $key => $value) {
// Switch goes here
}
Then inside this for-each you can do switch, where you use the value of $key.
How you are going to tackle this one, I haven't figured out at the moment...
[EDIT]
I would stick with the if-elseif version - if you only have those two values to check for :)
I think you misunderstand the switch() statement. It is a special case of if... else if... else if for comparing a single variable to a possible set of values. You can't include conditions (expressions that evaluate to a boolean) in the case statements. See http://www.php.net/manual/en/control-structures.switch.php for examples.
EDIT:
I must take a minute to rail against the abuse of the switch statement that is as follows:
$a=1;
$b=2;
switch(true) {
case ($a==1):
echo "first test passed";
break;
case ($b==2):
echo "second test passed";
break;
}
This compares "true" to each of the boolean results of the expressions below. Both conditions are true, the first one executes, and the break; statement skips the second one. Technically functional, wildly misleading, and I'd throttle the guy who left me this code to debug. Absolutely abominable practice. By contrast, if you switch on a value like ($a) or ($a -3) and your case statements contain comparison values like 5 and 7, or "A" and "B", a good IDE will warn you that you have duplicate case statements. You can be sure that exactly one of the case statements passes the comparison. And the people who maintain your code in future won't have to hunt you down or curse your name. Please don't use switch() this way. If you need to do it like this, use if... else if... for readability. In this way it is obvious that the tests must be checked in order and the flow of execution will be transparent.
I'm using switch statement on $_POST method and my script runs correctly but I think my code is not in a right way.
Here's my code:
<?php
switch(isset($_POST))
{
case isset($_POST['A']):
//do something
break;
case isset($_POST['B']):
//do something
break;
case isset($_POST['C']):
//do something
break;
}
?>
my script runs correctly but I think my switch statement is not GOOD enough. Is there more simplier way or BETTER way using switch statement and $_POST method?
It's horrible but I prefer this than if-else-evil-chain:
switch(true)
{
case isset($_POST['A']):
//do something
break;
case isset($_POST['B']):
//do something
break;
case isset($_POST['C']):
//do something
break;
}
check this out ;)
if (!empty($_POST)) {
switch ($_POST) {
case $_POST['A']:
#do something;
break;
case $_POST['B']:
#do something;
break;
case $_POST['C']:
#do something;
break;
}
}
Maybe you mean something similar?
<?php
if(isset($_POST['A'])){
// do something
}
if(isset($_POST['B'])){
// do something
}
if(isset($_POST['C'])){
// do something
}
?>
(This executes all the different matching branches instead of only the first one. Change the non-first if's to elseif if you want execute only the first matching branch.)
A nice way of putting a switch (){ case: } method is:
if (condition){
// Do Something
}elseif(condition){
// Do Something
}elseif(condition){
// Do Something
}
This chain, is horrible to look at, but something I would suggest using in your unique case, alternativley you could go with #lame-up-ducks answer, but this is what i'd personally recommend using
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) {
// ...
}
}
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
}