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.
Related
as a heads up I'm new at coding.
I'm trying to make a switch statement that will give the user the number that they have inputted into its proper roman number (only numbers from 1-10).
<form action="#" method="post">
Type a number from 1-10. <input type="text" name="num"/>
<input type="submit" name="submit">
</form>
<?php
switch (isset($_POST['submit'])) {
//$num = (int)$_POST["num"];
case 1:
echo "I";
break;
case 2:
echo "II";
break;
case 3:
echo "III";
break;
case 4:
echo "IV";
break;
case 5:
echo "V";
break;
case 6:
echo "VI";
break;
case 7:
echo "VII";
break;
case 8:
echo "VIII";
break;
case 9:
echo "IX";
break;
case 10:
echo "X";
break;
}
?>
Currently, this is what I have but I don't know of a way to get the switch statement to use the number that was provided by the user. Any help?
Thanks in advance.
The input that the user will enter a number in it has a name attribute of 'num', so to get what the user has entered, you'll use $_POST['num'].
// if the form has been submitted
if(isset($_POST['submit'])) {
$num = (int) $_POST['num'];
switch($num) {
case 1:
echo "I";
break;
case 2:
echo "II";
break;
case 3:
echo "III";
break;
case 4:
echo "IV";
break;
case 5:
echo "V";
break;
case 6:
echo "VI";
break;
case 7:
echo "VII";
break;
case 8:
echo "VIII";
break;
case 9:
echo "IX";
break;
case 10:
echo "X";
break;
default:
echo 'wrong number or you probably entered a number less than 1 or higher than 10';
}
}
First you make sure you have a something
Notice I am using $_POST['num']
$num = $_POST['num'] ?? 0;
Now you check
switch($num){
case 1:
echo 'I';
break;
case 2:
echo 'II';
break;
...
...
I would do it a bit differently, and even that is not the most efficiet transformation.
echo (([1=>'I', 2=>'II',3=>'III',....,9=>'IX'])[$_POST['num']]) ?? '';
isset($_POST['submit']) returns a boolean, which is not the integer in the range 1-10 that your switch statement expects. You probably meant to use $_POST['num'].
An array is a more compact way to encapsulate your logic instead of a long and potentially error-prone switch statement. Each array index maps to a numeral as follows:
<form action="#" method="post">
Type a number from 1-10. <input type="text" name="num">
<input type="submit" name="submit">
</form>
<?php
$numerals = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X'];
if (isset($_POST['num'])) {
echo isset($numerals[$_POST['num']]) ? $numerals[$_POST['num']] : "error";
}
?>
You can use the following solution to solve your problem:
$input = $_POST['num'];
if($input){
switch($input) {
....
}
}
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
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;
}
I have this code done, however it is not working the way I would like. I am trying to color a piece of a string. The color is decided by a function getcolor, which is decided by a function called raw transform, which will transforma raw score into a score from 1-9 for my switch case. Can anyone offer some help? $col is assigned by another function- for arguments sake lets say it is defined as: $col= 0.
<?php
$raw= 650;
function rawtransform($raw) {
$score = (int)($raw/50)-9;
}
//==========================================================================
// Function to decide which color system //
//==========================================================================
function getcolor($score, $col)
{
switch ($score){
// to return the function best way is to declare the case outcome as a variable eg.$truecol
case 1: /*500-550(Raw Score)*/
$truecol="<span style=\"color: hsl($col,100%,90%);\">";
break;
case 2: //550-600
$truecol="<span style=\"color: hsl($col,100%,80%);\">";
break;
case 3: //600-650
$truecol="<span style=\"color: hsl($col,100%,70%);\">";
break;
case 4: //650-700
$truecol="<span style=\"color: hsl($col,100%,60%);\">";
break;
case 5: //700-750
$truecol="<span style=\"color: hsl($col,100%,50%);\">";
break;
case 6: //750-800
$truecol="<span style=\"color: hsl($col,100%,40%);\">";
break;
case 6: //800-850
$truecol="<span style=\"color: hsl($col,100%,30%);\">";
break;
case 7: //850-900;
break;
case 8: //900-950
$truecol="<span style=\"color: hsl($col,100%,20%);\">";
break;
case 9: //950-1000
$truecol="<span style=\"color: hsl($col,100%,10%);\">";
break;
}
}
$query="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC";
$seq=chunk_split($query,50,"<br />");
getcolor($score);
function colorSequence ($seq,$position,$truecol,$TFBSlength){
$nucleotides = str_split($seq);
foreach ($nucleotides as $index => $nucl){
if ($index == $position){
echo $truecol;
}
if ($index == $position + $TFBSlength){
echo "</span>";
}
echo $nucl;
}
echo "\n";
}
colorSequence($seq,49,$truecol,1);
?>
The output does not include the coloring of the selcted nucleotides. Anyone know why?
You do not assign the return value of getcolor($score); to a variable. I bet it should be like $truecol = getcolor($score); before calling colorSequence($seq,49,$truecol,1);.
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 :)