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?
Speed: A switch statement might prove to be faster than ifs provided number of cases are good. If there are only few cases, it might not effect the speed in any case.
The PHP switch Statement Use the switch statement to select one of many blocks of code to be executed.
The if-else statement is used to choose between two options, but the switch case statement is used to choose between numerous options. If the condition inside the if block is false, the statement inside the else block is executed. If the condition inside the switch statement is false, the default statements are run.
The switch-case statement is an alternative to the if-elseif-else statement, which does almost the same thing. The switch-case statement tests a variable against a series of values until it finds a match, and then executes the block of code corresponding to that match.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With