PHP: Breaks in default case switches? - php

switch ($var) {
case 0:
// Do something...
break;
case 1:
// Do something...
break;
default:
// Do something...
break;
}
I've seen some people use break at the end of the default case. Since the default case is the last case that's executed when triggered, is there any need to have a break there? I'm guessing it's just done out of common practice or is there another reason?

There's no reason its required so long as the default is at the end of the switch statement. Note that the default doesn't need to be the last case: http://codepad.viper-7.com/BISiiD
<?php
$var = 4;
switch($var)
{
default:
echo "default";
break;
case 4:
echo "this will be executed";
break;
}

Related

Multiple Switch Statements

Okay, I have one PHP file which needs to contain several switch($_GET['']) statements. For example: switch($_GET['id']), switch($_GET['open']), switch($_GET['number'])... Do I have to close it like:
switch($_GET['id'])
{
}
Or:
switch($_GET['open'])
{
};
One below another with or without semicolon?
This is my index.php:
It does not fully work. My php file is like this (Index.php):
<?php
// THE MAIN SITE
switch($_GET['open'])
{
default: include("Home-Page.php");
case 'Site': include("LetsStart/Pages/Home.php"); break;
case 'Links: switch ($_GET['topics'])
{
default: include("LetsStart/Pages/Links.php"); break;
case 'Tourism': include("LetsStart/Pages/Tourism.php"); break;
case 'Finance': include("LetsStart/Pages/Finance.php"); break;
case 'Health Care': include("LetsStart/Pages/HealthCare.php"); break;
}
break;
case 'About Us': switch ($_GET['details'])
{
default: include("LetsStart/Pages/AboutUs.php"); break;
case 'What We Do': include("LetsStart/Pages/WWD.php"); break;
case 'Our History': include("LetsStart/Pages/OurHistory.php"); break;
}
break;
}
// ENCYCLOPEDIA
switch($_GET['letter'])
{
case 'B': switch($_GET['term'])
{
default: include("LetsStart/Pages/TheEncyclopedia/Letter-B-Main.php"); break;
case 'Term 1': include("LetsStart/Pages/TheEncyclopedia/B/1.php"); break;
case 'Term 2': include("LetsStart/Pages/TheEncyclopedia/B/2.php"); break;
case 'Term 2': include("LetsStart/Pages/TheEncyclopedia/B/3.php"); break;
}
break;
}
?>
It keeps loading my home page and the first page from the second switch.
You do not need a semicolon after the closing bracket of a switch statement (same as an if statement).
You don't need semicolon, because the $_GET['id'] is a variable, not a string. Read this http://www.w3schools.com/php/php_switch.asp

Check if an array field is set in a switch statement

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";
}

Check several field to execute switch case

I have a code to check through several fields to execute certain code as below:
switch($tag1 || $tag2 || $tag3 || $tag4 ||$tag5){
case "satay":
$imgput = "/home/uploads/sandbox/jovine/Food/tags/satay/$img_name";
break;
case "digitalmarketing":
$imgput = "/home/uploads/sandbox/jovine/Food/tags/interactive_marketing/$img_name";
break;
case "chillicrab":
$imgput = "/home/uploads/sandbox/jovine/Food/tags/chilli_crab/$img_name";
break;
case "chickenrice":
$imgput = "/home/uploads/sandbox/jovine/Food/tags/chicken_rice/$img_name";
break;
case "chendol":
$imgput = "/home/uploads/sandbox/jovine/Food/tags/chendol/$img_name";
break;
}
But it does not work.
Anyone can help?
Switch support one value only. Only IF condition can have OR and AND condition.
$tags = get the tag value.
switch($tags){
case "satay":
$imgput = "/home/uploads/sandbox/jovine/Food/tags/satay/$img_name";
break;
case "digitalmarketing":
$imgput = "/home/uploads/sandbox/jovine/Food/tags/interactive_marketing/$img_name";
break;
case "chillicrab":
$imgput = "/home/uploads/sandbox/jovine/Food/tags/chilli_crab/$img_name";
break;
case "chickenrice":
$imgput = "/home/uploads/sandbox/jovine/Food/tags/chicken_rice/$img_name";
break;
case "chendol":
$imgput = "/home/uploads/sandbox/jovine/Food/tags/chendol/$img_name";
break;
}
The following should do the trick for you:
<?php
$tag1='satay';
$tag2='test2';
$tag3='digitalmarketing';
function isItThere($myTag)
{
switch($myTag)
{
case "satay":
$imgput = "/home/uploads/sandbox/jovine/Food/tags/satay/$img_name";
echo $imgput;
break;
case "digitalmarketing":
$imgput = "/home/uploads/sandbox/jovine/Food/tags/interactive_marketing/$img_name";
echo $imgput;
break;
// etc etc
}
}
for($i=1;$i<4;$i++)
{
isItThere(${'tag'.$i});
}
?>
I have basically set up a small function that contains the switch statement and written a simple loop to test the variables.
As I said in my comment, you can't use more than one variable in the switch statement, but this will provide you a nice clean workaround to do the same thing without the need to write many long statements.

improving a routing class*

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 :)

Can I have multiple cases that do the same thing?

The first one is definitely something that works, but which one below is the efficient way?
switch($type) {
case 1:
print 'success';
break;
case 2:
print 'success';
break;
case 3:
print 'success';
break;
case 4:
print 'success for type 4';
break;
}
Since 1, 2 and 3 print do the same, can I do this?
switch($type) {
case 1, 2, 3:
print 'success';
break;
case 4:
print 'success for type 4';
break;
}
or
switch($type) {
case 1:
case 2:
case 3:
print 'success';
break;
case 4:
print 'success for type 4';
break;
}
switch($type)
{
case 1:
case 2:
case 3:
print 'success';
break;
case 4:
print 'success for type 4';
break;
}
Is the way to go!
PHP manual lists an example like your 3rd for switch:
<?php
switch ($i) {
case 0:
case 1:
case 2:
echo "i is less than 3 but not negative";
break;
case 3:
echo "i is 3";
}
?>
I agree with the others on the usage of:
switch ($i) {
case 0: //drop
case 1: //drop
case 2: //drop
echo "i is 0, 1, or 2";
break;
// or you can line them up like this.
case 3: case 4: case 5:
echo "i is 3, 4 or 5";
break;
}
The only thing I would add is the comments for the multi-line drop through case statements, so that way you know it's not a bug when you (or someone else) looks at the code after it was initially written.

Categories