I have a switch statement set up which checks the value in an array field. I also want to perform slightly different logic if the array has no field with that name.
I can write the code like this, which works, but looks a little messy in my mind:
if (!isset($_GET['action']))
{
require('menu.html');
}
else
{
switch ($_GET['action'])
{
case 'debug':
require('core/actions/debug.php');
break;
case 'submit':
require('core/actions/submit.php');
break;
case 'admin':
header("Location: /login");
break;
}
}
But would it be possible for me to instead move the logic from the if statement and combine it with with my switch logic?
In JavaScript, I could do case undefined: ... as just one of the cases. Can I do something similar in PHP?
If $_GET['action'] is empty, or does have value, but its not any of the ones you want, you can do this.
switch ($_GET['action'])
{
.............
case "":
echo "empty or not setted";
break;
}
But if $_GET['action'] is not setted it will throw notices on every comparison (but it will enter in case '' anyway).
To not show the notices you could do:
switch (#$_GET['action'])
But please, don't do that!
You could do the super-switch-crazy way too:
switch(true){
case !empty($_GET['action']):
switch ($_GET['action'])
{
.............
}
break;
default:
echo "not setted or empty";
break;
}
Edit:
As #IQAndreas pointed out in the comments a interest solution could be:
switch (true)
{
case (!isset($_GET['action']):
require('menu.html');
break;
case ($_GET['action'] == 'debug'):
require('core/actions/debug.php');
break;
case ($_GET['action'] == 'submit'):
require('core/actions/submit.php');
break;
case ($_GET['action'] == 'admin'):
header("Location: /login");
break;
}
But the best way IMO to handle this situation is doing what you are already doing (checking if the var is empty or setted, before the switch..case)
if (isset($_GET['action'])){
switch ($_GET['action'])
{
.............
case "":
echo "empty";
break;
}
} else {
echo "not setted";
}
Related
is there a way to go from switch case to execute what is in default?
switch ($_REQUEST['action']) {
case 'edit':
if (isset($_REQUEST['id']) {
doSomething();
else {
goToDefault();
}
break;
case 'list':
...
break;
default:
doDefaultStuff();
break;
}
In the example, I want in the first case's else to go execute what is in default of switch.
Is that possible, or should I use different approach?
You can do that with goto, but I wouldn't recommend that.
$action = 'edit';
$id = null;
switch ($action) {
case 'edit':
if ($id) {
doSomething();
} else {
goto default_action;
}
break;
case 'list':
break;
default:
default_action: echo "doing default stuff";
break;
}
Demo: https://3v4l.org/X71e8
You can use switch(true) instead:
switch (true) {
case $_REQUEST['action'] === 'edit' && isset($_REQUEST['id']):
doSomething();
break;
case $_REQUEST['action'] === 'list':
// ...
break;
default:
doDefaultStuff();
break;
}
I have the following switch statement.
The URL contains a referral ID e.g twitter, facebook or an email e.g mail#mail.com. This is stored as $ref
I have the following switch statement:
switch ($ref) {
case "twitter":
echo "twitter";
break;
case "facebook":
echo "facbeook";
break;
case "blog":
echo "blog";
break;
case strstr($ref,'#'):
echo "email = ".$ref;
default:
echo "no referral found";
break;
}
However if URL is passed with nothing (e.g just www.mything.co.uk) then I wish to go to the default case.
Instead, I get the following output:
email = no referral found
Why does the default also include the text I set for case strstr($ref,'#') ?
OP question: "Why does the default also include the text I set for case strstr($ref,'#') ?"
Answer: there's no break; following the output, and thus falls through to the default case.
UPDATE: Addressing the issue of putting a statement within a case, I'm also including an easy work-around:
switch ($ref) {
case "twitter":
echo "twitter";
break;
case "facebook":
echo "facbeook";
break;
case "blog":
echo "blog";
break;
default:
if (strstr($ref,'#')) {
echo "email = ".$ref;
} else {
echo "no referral found";
}
break;
}
When $ref is an empty String, then strstr($ref,'#'); returns an empty string too, this is why the case strstr($ref,'#'): matches the switch input $ref.
The problem is, you can't even use a email validation function like
filter_var($ref, FILTER_VALIDATE_EMAIL)
That would return false in case of an empty input instead of an empty string, but switch does loose comparison, meaning that an "" == false would return true:
http://php.net/manual/en/types.comparisons.php#types.comparisions-loose
Thus the only solution I see is to use an if statement using the === operator:
if($ref == 'twitter') {
echo "twitter";
} else if($ref == 'facebook') {
echo "facbeook";
} else if($ref == 'blog') {
echo "blog";
} else if($ref === filter_var($ref, FILTER_VALIDATE_EMAIL)) {
echo "email = ".$ref;
} else {
echo "no referral found";
}
That's because your test is performed like if ($ref == strstr($ref, '#')), where strstr returns false which equals an empty string. You cannot really use dynamic comparisons in switch statements. Use if..else if you need that. Alternatively, abuse switch a bit:
switch (true) {
case $ref == 'twitter':
..
case strstr($ref, '#'):
..
}
That will work:
case (strstr($ref, '#') ? true : false):
But it's not really good of practice.
For example I have this:
switch ($action)
{
case 'my_action':
doSomething();
break;
case 'second_action':
if ($this_is_true)
{
$action = 'my_action';
}
else
{
doSomethingElse();
}
break;
}
Is the example above going to go through the switch again and then call the first case my_action if the second case second_action has $this_is_true variable set to true?
If this doesn't work, what would be an alternative?
You can try something like this:
switch ($action)
{
case 'my_action':
case 'second_action':
if ($this_is_true || $action=='my_action')
{
doSomething();
}
else
{
doSomethingElse();
}
break;
}
When $action is equal to 'my_action' it will run through the case, as it finds no break sentence then it will run through the second case until it finds the break sentence.
Please give a look to example #3 in http://php.net/manual/en/control-structures.switch.php to find out more about no breaking switch cases.
No it won't. Just call doSomething(); in the 'second_action' case.
I wouldn't use a switch in this simple case, but if it is very long then maybe:
$do = false;
switch ($action)
{
case 'my_action':
$do = true;
break;
case 'second_action':
if ($this_is_true)
{
$action = 'my_action';
$do = true;
}
else
{
doSomethingElse();
}
break;
}
if($do) { doSomething(); }
Try to do it this way:
do {
switch ($action)
{
case 'my_action':
$this_is_true = false;
doSomething();
break;
case 'second_action':
if ($this_is_true)
{
$action = 'my_action';
}
else
{
doSomethingElse();
}
break;
}
} while($this_is_true);
Do not forget to switch $this_is_true to false where it needed!
But this code is not beautiful... May be you better to refactor your code.
I have following code:
switch(true)
{
case (something):
{
break;
}
case (something2):
{
break;
}
case (something3):
{
break;
}
}
Also the switch statement must check what one of cases give a TRUE, that is not the problem, the problem is, that i have now a case, where inside of case ... break; after checking other data, i wish to choose other switch-case, the one, that following him.
I have try do this:
switch(true)
{
case (something):
{
break;
}
case (something2):
{
if(check)
{
something3 = true;
continue;
}
break;
}
case (something3):
{
break;
}
}
But PHP do not wish to go in to the case (something3): its break the full switch statement. How i can pass the rest of code of one case and jump to the next?
This is what's called a "fall-through". Try organizing your code with this concept.
switch (foo) {
// fall case 1 through 2
case 1:
case 2:
// something runs for case 1 and 2
break;
case 3:
// something runs for case 3
break;
}
Using your code:
switch(true)
{
case (something):
{
break;
}
case (something2):
{
if(check) {
something3 = true;
}
else {
break;
}
}
case (something3):
{
break;
}
}
This will get to case something2 and run your check. If your check passes then it doesn't run the break statement which allows the switch to "fall through" and also do something3.
case (something2):
{
if(!check)
{
break;
}
}
Try this:
switch(true) {
case (something):
{
break;
{
case (something2):
{
if (!check) {
break;
}
}
case (something3):
{
break;
}
}
I had some similar situation and I came up with a solution which in your case would be like this:
switch(true)
{
case (something):
{
break;
}
case (something2):
{
if(!check)
{
break;
}
}
case (something3):
{
break;
}
}
You see that instead of checking the conditions to go to the next case, we checked if we should ignore the current one.
I use the class below to route all requests for php on my web application. Can I improve upon this?
/*route*/
class route
{
function __construct($a)
{
if(isset($_FILES['ufile']['tmp_name'])) // handles file uploads
{
new upload();
}
elseif(isset($_POST['a'])) // handles AJAX
{
$b=$_POST['a'];
switch($b)
{
case '0':
new signin();
break;
case '1':
new signup();
break;
case '2':
session::finish();
break;
case '3':
new bookmark('insert');
break;
case '3a':
new bookmark('delete');
break;
case '4':
new tweet();
break;
default:
echo "ajax route not found";
break;
}
}
elseif($a!=0) // handles views
{
new view($a);
}
else
{
// route not found
}
}
}
Verification(passes)
/*ROUTE
// Test Code - create entry
new route(0);
new route(1);
$_FILES['ufile']['tmp_name']='test file';
new route(0);
unset($_FILES['ufile']['tmp_name']);
$_POST['a']=0;
new route(0);
// Test Cases
// Case 0: echo "not routed: <br>";
// Case 1: echo "view created: $a <br>";
// Case 2: echo "file uploaded <br>";
// Case 3: echo "ajax responded: <br>";
*/
public static function route($a)
{
// The first if statement is redundant this line will accomplish the
// same as the if/else because if post[a] is not set it will become null
$b=$_POST["a"];
// now that b is a, it's really one switch statement
if( $b==0 && $a==0 )
switch( $b )
{
case '0':
new signin();
break;
case '1':
new signup();
general::upload();
break;
case '2':
session::finish();
break;
case '3':
new bookmark('insert');
break;
case '3a':
new bookmark('delete');
break;
case '4':
new tweet();
break;
default:
view::posts_all();
break
}
}elseif( $a==1 )
view::bookmarks();
else
view::posts_all();
Give that a go, Good luck. (A side note: the quotation marks on the numeric cases are optional, the 3a is not. I left them in there because they were in the original. You could reduce it further by getting rid of $b entirely and running the switch on $_POST['a'] )
if/else statement lets you set particular condition evaluations, while switch/case only lets you set some particular values that the variable may assume (i.e. in a switch/case you cannot say something like $b > 10).
Except for that, there's no much difference between if/else or switch/case.
I suggest you to you use switch/case construct, since you are just comparing $b with a group of constants.
Besides, remember premature optimization is the root of all evil :)